逻辑:前端上传图片调后端接口,后端上传成功后返回一个路径,再把这个路径放在标签里,最后一起保存入数据库。其中生成的UUID是为了上传照片解决重名的问题
/**
* 图片上传
* @param file
* @param request
* @param response
* @return
*/
@RequestMapping(value = "/uploadPhoto",method = RequestMethod.POST)
@ResponseBody
public Object uploadPhoto(@RequestParam(value = "file",required = false)MultipartFile file, HttpServletRequest request, HttpServletResponse response){
String prefix="";
String dateStr="";
String originalName="";
//生成UUID
String uuid=UUID.randomUUID().toString().replace("-","");
//保存上传
OutputStream out = null;
InputStream fileInput=null;
try{
if(file!=null){
// originalName = file.getOriginalFilename();
originalName = uuid+file.getOriginalFilename();
String filepath = "E:\\benke\\lx\\travel\\src\\main\\resources\\static\\images\\strategy\\" + originalName;
//E:\benke\lx\travel\src\main\resources\static\images\hotel\captcha.jpg
filepath = filepath.replace("\\", "/");
File files=new File(filepath);
//打印查看上传路径
System.out.println(filepath);
if(!files.getParentFile().exists()){
files.getParentFile().mkdirs();
}
file.transferTo(files);
}
}catch (Exception e){
}finally{
try {
if(out!=null){
out.flush();
out.close();
}
if(fileInput!=null){
fileInput.close();
}
} catch (IOException e) {
}
}
Map map2=new HashMap<>();
Map map=new HashMap<>();
map.put("code",0);
map.put("msg","");
map.put("data",map2);
map2.put("src","/static/images/strategy/"+originalName);
return map;
}