1. 程式人生 > 其它 >圖片上傳後端邏輯程式碼

圖片上傳後端邏輯程式碼

邏輯:前端上傳圖片調後端介面,後端上傳成功後返回一個路徑,再把這個路徑放在標籤裡,最後一起儲存入資料庫。其中生成的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<String,Object> map2=new HashMap<>();
Map<String,Object> map=new HashMap<>();
map.put("code",0);
map.put("msg","");
map.put("data",map2);
map2.put("src","/static/images/strategy/"+originalName);

return map;
}