MultipartFile upload pictures to the webapps directory under the Linux server Tomcat

First contact with linux server, upload the picture when it came to do some pit, do some day finally succeeded, record it

 

/**
* 上传图片
*
* @param request
* @param file
* @return
*/
@RequestMapping(value = "uploadImg", method = RequestMethod.POST)
@ResponseBody
public String uploadImg1(HttpServletRequest request, MultipartFile file) {
Gson gson = new Gson();
List<String> pathList = new ArrayList<String>();
String pic_path;
if (null != file) {
// 文件原名称
String myFileName = file.getOriginalFilename();
String fileName = UUID.randomUUID().toString() + "." + myFileName.
substring(myFileName.lastIndexOf(".") + 1);
try {
String tomcat_path = System.getProperty("user.dir");
//获取tomcat中项目同级路径
String bin_path = tomcat_path.substring(tomcat_path.lastIndexOf("/") + 1, tomcat_path.length());
if (("bin").equals(bin_path)) {
pic_path = tomcat_path.substring(0, System.getProperty("user.dir").lastIndexOf("/")) + "/webapps" + "/upload" + "/uploadImg/";
} else {
pic_path = tomcat_path + "/webapps" + "/upload" + "/uploadImg/";
}
logger.info("上传图片的路径:" + pic_path + fileName);
File fileDir = new File(pic_path + fileName); if (! FileDir.exists ()) {
// create if it does not exist

fileDir.mkdirs ();
}
// the data in memory to disk
file.transferTo (filedir);
// Image Path ip: port / upload / uploadImg / image name

pathList.add (ImgConstant.ACCESS_IMAGE_URL + fileName);
            gson.toJson return (PathList); 
} the catch (IllegalStateException E) {
logger.error ( "Image Upload Error", E);
} the catch (IOException E) {
logger.error ( "Image Upload Error", E);
}
} {the else
System.out.println ( "upload is empty!");
}
return gson.toJson (PathList);
}

Guess you like

Origin www.cnblogs.com/hjyhjyhjy/p/11800811.html