控制器方法的返回值必须以String返回,再由js处理转换成json对象
$.ajaxFileUpload({
url: "/project/proj_conver_upload", // 需要链接到服务器地址
secureuri: false,
fileElementId: "fileBtn", // 文件选择框的id属性
data: {},
dataType: ‘json‘, // 服务器返回的格式,可以是json
complete: function(response, status) {
var responseText = response.responseText;
if (responseText.indexOf(">") != -1&& (responseText.indexOf("PRE") != -1 || responseText.indexOf("pre") != -1)) {
responseText = responseText.substring(responseText.indexOf(">") + 1, responseText.lastIndexOf("<"));
}
var data = eval("(" + responseText + ")");//转换成json对象
if(data.retCode!="200"){
showWarning(data.msg);
return;
}else{
$("#avaImg").attr("src", data.results);
$("#projFileName").val(fileName);
$("#ava").val(data.results);
$("#fileBtn").css("display", "block");
$("#projFileNameSpan").html("");
}
},
error: function(data, status, e) {
console.log(data.msg);
}
});
服务器中控制层:
@RequestMapping(value = "/proj_conver_upload",method = RequestMethod.POST,produces = { "text/html;charset=UTF-8" })
@ResponseBody
public String projConverUpload(@RequestParam(value = "fileBtn", required = true) MultipartFile file,
HttpServletRequest request,HttpServletResponse response) throws Exception {
response.setContentType("text/html");
response.setCharacterEncoding("UTF-8");
long size = file.getSize()/1014/1014;
LOG.debug("logoImgSize: "+ size+"M");
if(size>=2){
return JsonHelper.toJsonString(new Result(CodeConstant.RETCODE_500, "图片附件不能大于2M"));
}
String fileName = file.getOriginalFilename();
if(!FileHelper.isPic(fileName)){
return JsonHelper.toJsonString(new Result(CodeConstant.RETCODE_500, "请上传正确的图片格式"));
}
fileName = UUIDFileName(file.getOriginalFilename());
FileUploadUtil.transferTo(file, getTempDic(request), fileName);
Result<String> result = new Result<String>();
result.setResults(FileConstant.TEMP_FILE_ROOT+"/"+fileName);
return JsonHelper.toJsonString(result);
}
转载自同事工作笔记