说明jquery ajax上传图片
springmvc接收并保存到本地,并拼装图片url,返回给前端
前端接收到url后,回显图片
注意:
jquery版本不能太低,最好1.10以上
html
function update(){
var formData = new FormData();
formData.append("image",$("#image")[0].files[0]);
$.ajax({
url:'goods/upload', /*接口域名地址*/
type:'post',
data: formData,
contentType: false,
processData: false,
success:function(res){
console.log(res.data);
if(res.code==0){
$("#img").attr('src',res.data.imageURL);
imageURL=res.data.dbURL;
}else{
alert(res.msg);
}
},
error:function (XMLHttpRequest, textStatus, errorThrown) {
alert(XMLHttpRequest);
alert(textStatus);
alert(errorThrown);
}
})
}
java@RestController
@RequestMapping("/mgr/goods")
public class MgrGoodsCtrl {
@PostMapping("/upload")
public JsonResult upload(MultipartFile image,HttpServletRequest req) {
JsonDataResult> jr=new JsonDataResult();
String oFilename=image.getOriginalFilename();
String suffix=oFilename.substring(oFilename.lastIndexOf("."));
String newFilename=UUIDTools.randomUUID()+suffix;
//前台页面回显图片的url
String imageURL=req.getContextPath()+"/"+Key.UPLOAD_FOLDER+"/"+newFilename;
//保存到数据库中的url,为了保证通用,根路径为Key.UPLOAD_FOLDER
String dbURL=Key.UPLOAD_FOLDER+"/"+newFilename;
String contexPath= req.getSession().getServletContext().getRealPath("/");
File file=new File(contexPath,"upload");
if(!file.exists()) {
file.mkdirs();
}
File filePath=new File(file,newFilename);
try {
image.transferTo(filePath);
jr.setCode(0);
Map map=new HashMap();
map.put("imageURL", imageURL);
map.put("dbURL", dbURL);
jr.setData(map);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return jr;
}
}