MultipartFile 图片上传到Linux服务器Tomcat下的webapps目录

第一次接触 linux 服务器,做图片上传的时候遇到了些坑,搞了些天总算成功了,记录一下

/**
* 上传图片
*
* @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()) {
fileDir.mkdirs();
}
// 将内存中的数据写入磁盘
file.transferTo(fileDir);
//图片路径 ip:端口/upload/uploadImg/图片名

pathList.add(ImgConstant.ACCESS_IMAGE_URL + fileName);
            return gson.toJson(pathList);
} catch (IllegalStateException e) {
logger.error("图片上传错误", e);
} catch (IOException e) {
logger.error("图片上传错误", e);
}
} else {
System.out.println("上传内容为空!");
}
return gson.toJson(pathList);
}
原文地址:https://www.cnblogs.com/hjyhjyhjy/p/11800811.html