前台代码:
var imgData = new FormData();
imgData.append("imageType", $("#"+imgID).attr("data-type"));
imgData.append("typeName", $("#"+imgID).attr("data-name"));
imgData.append("imageFile", $("#" + fileID).get(0).files[0]);
$.ajax({
url: requestUrl,
type: "POST",
data: imgData,
contentType:false,
processData: false,
dataType: 'json', //json
success: function (result) {
if(result.code == "10000"){
// 图片上传成功
console.log("上传成功,图片路径------"+result.data.url)
} else{
console.log("上传失败")
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
console.log("ajax请求异常------")
}
});
后端代码:
/**
* api: 图片上传
* @return jsonString
*/
@RequestMapping(value = "/imageUpload.htm")
@ResponseBody
public String imageUpload(String imageType, MultipartFile imageFile, HttpSession session){
String result;
try {
if(Utils.isEmpty(imageType) || null == imageFile){
return JsonResponse.errorResult("缺少参数", null, null);
}
JSONObject resp = merchantController.imageUpload(imageType, systemConfig.getString("apiService.url"),
imageFile);
if ("10000".equals(resp.get("code"))) {
// 返回页面数据
Map<String, String> map = new HashMap<>();
map.put("url", systemConfig.getString("IMG_PATH") + resp.getString("photoUrl"));
result = JsonResponse.ok(map);
} else {
result = JsonResponse.errorResult("上传失败,请重试", "", "");
}
} catch (Exception e) {
e.printStackTrace();
result = JsonResponse.errorResult("上传失败,请重试", "9999", "系统异常," + e.getMessage());
}
return result;
}
请求一直出错,406 Not Acceptable,一直进的是 error 方法
修改了下后台的返回方式如下
/**
* api: 图片上传
* @return jsonString
*/
@RequestMapping(value = "/imageUpload.htm")
public void imageUpload(String imageType, MultipartFile imageFile, HttpSession session,HttpServletResponse response) throws IOException{
String result;
try {
if(null == imageFile){
result = JsonResponse.errorResult("缺少参数", null, null);
}else{
JSONObject resp = merchantController.imageUpload(imageType, systemConfig.getString("apiService.url"),
imageFile);
if ("10000".equals(resp.get("code"))) {
// 返回页面数据
Map<String, String> map = new HashMap<>();
map.put("url", systemConfig.getString("IMG_PATH") + resp.getString("photoUrl"));
result = JsonResponse.ok(map);
} else {
result = JsonResponse.errorResult("上传失败,请重试", "", "");
}
} catch (Exception e) {
e.printStackTrace();
result = JsonResponse.errorResult("上传失败,请重试", "9999", "系统异常," + e.getMessage());
}
PrintWriter writer = response.getWriter();
writer.write(result);
writer.flush();
writer.close();
}