Simple example of uploading a file

@ResponseBody
@RequestMapping("/uploadNoticeImg")
public String uploadNoticeImage(@RequestParam MultipartFile file,HttpServletRequest request) {
// URL to upload
//String path = AppPropertiesUtil.getValue("imgUrl");
String path = request.getSession().getServletContext().getRealPath("/")+"upload/";
path += DateUtil.getDate(new Date()) + "/";
//upload image
File newfile=new File(path);
newfile.mkdirs();

// image name after upload
String name=UUID.randomUUID().toString();
// image name before upload
String oldName=file.getOriginalFilename();
// suffix name
String extName=oldName.substring(oldName.lastIndexOf(".")+1, oldName.length());
File fileResoult= new File(path+"/"+name+"."+extName);
FileOutputStream  fop1 = null;
try {
fop1 = new FileOutputStream(fileResoult);
byte[] b=file.getBytes();
fop1.write(b);
fop1.flush();
fop1.close();
logger.info("====================upload picture success==========================");
} catch (Exception e) {
logger.error("====================upload picture error==========================");
e.printStackTrace ();
}finally {
if(null!=fop1){
try {
fop1.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace ();
}
}
}
//picture view address
String viewUrl=AppPropertiesUtil.getValue("domainImgUrl");
viewUrl += DateUtil.getDate(new Date()) + "/";
viewUrl=viewUrl+name+"."+extName;
logger.info("====================upload picture url is "+viewUrl);
return viewUrl;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325758606&siteId=291194637