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);
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM