您的位置:首页 > 编程语言 > Java开发

springmvc上传头像 ajax上传文件回显

2017-12-06 19:37 330 查看
<form >

                    <div class="original_image">

                        <input type="hidden" id="head_photo"  value="${member.head_photo}" />

                        <img src="${member.fixHeadPhoto}" id="photoView" style="width: 248px;height: 248px;">

                    </div>

                    <div class="file">
  <a href="javscript:;"><input type="file"  id="upload" name="file" onchange="uphoto();">上传头像</a>

                      <p>只支持JPG、PNG、GIF,大小不超过5M</p>
<div class="sure">

                        <input type="button" value="确定" onclick="updatephoto();">

                        <input type="reset" value="取消" class="cancel">

                    </div>
</div>
                </form>

function uphoto(){
var formData = new FormData();
formData.append("file",$("#upload")[0].files[0]);
$.ajax({

        type : "post",

        url : ctx+"/personal/uploadPhoto.shtml",

        data : formData, 

        // 告诉jQuery不要去处理发送的数据

        processData : false, 

    // 告诉jQuery不要去设置Content-Type请求头

    contentType : false,

        success : function(data) {

            if(data.flag){

            $("#photoView").attr("src",data.targetUrl);

            console.log(data.relPath);

            $("#head_photo").val(data.relPath);

            }else{

            parent.layer.msg(data.error);

            }

        }

    });

}

function updatephoto(){
$.ajax({

        type : "post",

        url : ctx+"/personal/updateHeadPhoto.shtml",

        data : {

        head_photo : $("#head_photo").val()

        }, 

        success : function(data) {

            if(data.flag){

            parent.layer.msg(data.msg,{time:1000},function(){

                    window.location.reload();

                });

            }else{

            parent.layer.msg(data.msg);

            }

        }

    });

}

@RequestMapping(value = "uploadPhoto", produces = "application/json;charset=UTF-8")
@ResponseBody

    public String  fileUpload2(@RequestParam("file") MultipartFile[] upload) throws IOException {
JSONObject result = new JSONObject();
result.put("flag", false);
try {
String rootPath = SysConfigManager.getInstance().getText("/config/sys/rootPath");
String hostUrl = SysConfigManager.getInstance().getText("/config/sys/host");
String fileType = "";
String fileName = "";
String prefix = "";
File copyFile = null;
Long maxUploadsize = 5242880L;//最大5兆
for(MultipartFile each:upload){
int index = each.getOriginalFilename().lastIndexOf(".");
if (index > -1) {
fileType = each.getOriginalFilename().substring(index + 1);
}
fileName = UUID.randomUUID().toString();
prefix =  "/data/profile/head_photo/" + fileType + DateUtils.getNowTimeString();
copyFile = new File(rootPath + prefix + fileName + "." + fileType);
fileType = fileType.toLowerCase();
if(fileType.equals("jpg")||fileType.equals("png")||fileType.equals("gif")){
if(maxUploadsize >= each.getSize()){
if (!copyFile.getParentFile().exists()) {
copyFile.getParentFile().mkdirs();
}
//放图片
each.transferTo(copyFile);
String thumbSize = null;//缩略图尺寸
String thumbPath = null;//缩略图路径
thumbSize = SysConfigManager.getInstance().getText("/config/user/head_photo/thumbSize");//略图尺寸
//缩放图
thumbPath = prefix + fileName + "_" + thumbSize + "." + fileType;
JMagickScale.cutImage(Integer.parseInt(thumbSize.split("x")[0]), Integer.parseInt(thumbSize.split("x")[1]), copyFile.getAbsolutePath(),rootPath + thumbPath );
result.put("flag", true);
result.put("relPath",thumbPath);
result.put("targetUrl",hostUrl+thumbPath);
}else{
result.put("flag", false);
result.put("error", "请上传小于5M的图片!");
}
}else{
result.put("flag", false);
result.put("error", "请上传JPG、PNG、GIF格式的图片!");
}

}
} catch (Exception e) {
logger.error("上传头像出现异常"+e.getMessage());
result.put("msg", "上传头像失败!");
e.printStackTrace();
}

        

        return JSON.toJSONString(result);

    }

@RequestMapping(value = "updateHeadPhoto", produces = "application/json;charset=UTF-8")
@ResponseBody
public String updateHeadPhoto(String head_photo){
JSONObject result = new JSONObject();
result.put("flag", false);
try {
InterMember in = interMemberService.getInterMemberByMemId(SecurityCommonUtils.getCurrentMember().getMem_id());
in.setHead_photo(head_photo);
interMemberService.updateInterMember(in);
SecurityCommonUtils.getCurrentMember().setHead_photo(head_photo);
result.put("msg", "修改成功!");
result.put("flag", true);
} catch (Exception e) {
logger.error("修改头像出现异常"+e.getMessage());
result.put("msg", "修改失败!");
e.printStackTrace();
}
return JSON.toJSONString(result);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: