JAVA 上传图片到 服务器(Tomcat)目录下

package com.shangjian.cms.utils; import java.io.File; import java.util.HashMap; import java.util.Map; import java.util.UUID; import org.apache.commons.io.FilenameUtils; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.multipart.MultipartFile; import com.shangjian.cms.bean.Picture; public class ImgToProjectTools { //图片上传路径 String url2 = "E:/Shang-Jian/Git/CHS/src/main/webapp/view/GrowthRecordImg"; String url3 = "E:/Shang-Jian/Git/CHS/src/main/webapp/view/pictures"; String CMSURL = "E:/Shang-Jian/Git/CMS/CMS/src/main/webapp/view/pictures"; /** * 处理图片组【两张】上传至项目 * @param pictureFile * @return * @throws Exception */ public Map dataImg(@RequestParam("pictureFile")MultipartFile[] pictureFile) throws Exception{ Map imgMap = new HashMap(); String img_url = null; String img_url2 = null; if (pictureFile != null && pictureFile.length > 0) { for (int i = 0; i < pictureFile.length; i++) { MultipartFile file = pictureFile[i]; if(file.getName()== ""){}else{ //保存图片 String url = saveImgTwo(file); //分开保存两个imgurl两个字段 if(i==0){ img_url = url; }else if(i==1){ img_url2 = url; } } } } imgMap.put("img_url", img_url); imgMap.put("img_url2", img_url2); return imgMap; } //保存图片方法 public String saveImgTwo(MultipartFile pictureFile){ if(pictureFile.getSize()==0){ return null; }else{ String pic_path; //获取Tomcat服务器所在的路径 String tomcat_path = System.getProperty("catalina.home"); System.out.println(tomcat_path); //获取Tomcat服务器所在路径的最后一个文件目录 String bin_path = tomcat_path.substring(tomcat_path.lastIndexOf("\\") + 1, tomcat_path.length()); System.out.println(bin_path); //若最后一个文件目录为bin目录,则服务器为手动启动 if (("bin").equals(bin_path)) {//手动启动Tomcat时获取路径为:D:\Software\Tomcat-8.5\bin //获取保存上传图片的文件路径 pic_path = tomcat_path.substring(0, System.getProperty("catalina.home").lastIndexOf("\\")) + "\\webapps" + "\\App_user_Photo\\"; } else {//服务中自启动Tomcat时获取路径为:D:\Software\Tomcat-8.5 pic_path = tomcat_path + "\\webapps" + "\\CHS" + "\\view" + "\\GrowthRecordImg\\"; } String uuid=UUID.randomUUID().toString().replaceAll("-", ""); //项目部署使用 String strPath = pic_path; //本地使用 //String strPath = url2; //String strPath = Config.PATH; String suffix = pictureFile.getOriginalFilename().substring(pictureFile.getOriginalFilename().lastIndexOf(".")); suffix = suffix.toLowerCase(); if (suffix.equals(".jpg") || suffix.equals(".jpeg") || suffix.equals(".png") || suffix.equals(".gif")) { String fileName = uuid + suffix; File targetFile = new File(strPath, fileName); if (!targetFile.getParentFile().exists()) { //注意,判断父级路径是否存在 targetFile.getParentFile().mkdirs(); } long size = 0; //保存 try { pictureFile.transferTo(targetFile); size = pictureFile.getSize(); } catch (Exception e) { e.printStackTrace(); }return fileName; } else { /* JSONObject jsonObject = new JSONObject(); jsonObject.put("error", 1); */ return "图片格式不正确,保存失败!"; } } } //保存图片方法 public Picture saveImgThree(MultipartFile pictureFile){ if(pictureFile.getSize()==0){ return null; }else{ Picture pc = new Picture(); //图片大小pictureFile.getContentType(); pc.setOld_name(pictureFile.getOriginalFilename()); pc.setSize(pictureFile.getSize()); String pic_path; //获取Tomcat服务器所在的路径 String tomcat_path = System.getProperty("catalina.home"); System.out.println(tomcat_path); //获取Tomcat服务器所在路径的最后一个文件目录 String bin_path = tomcat_path.substring(tomcat_path.lastIndexOf("\\") + 1, tomcat_path.length()); System.out.println(bin_path); //若最后一个文件目录为bin目录,则服务器为手动启动 if (("bin").equals(bin_path)) {//手动启动Tomcat时获取路径为:D:\Software\Tomcat-8.5\bin //获取保存上传图片的文件路径 pic_path = tomcat_path.substring(0, System.getProperty("catalina.home").lastIndexOf("\\")) + "\\webapps" + "\\App_user_Photo\\"; } else {//服务中自启动Tomcat时获取路径为:D:\Software\Tomcat-8.5 pic_path = tomcat_path + "\\webapps" + "\\CMS" + "\\view" + "\\pictures\\"; } String uuid=UUID.randomUUID().toString().replaceAll("-", ""); //项目部署使用 String strPath = pic_path; //本地使用 //String strPath = CMSURL; pc.setPath(strPath); //String strPath = Config.PATH; String suffix = pictureFile.getOriginalFilename().substring(pictureFile.getOriginalFilename().lastIndexOf(".")); suffix = suffix.toLowerCase(); pc.setExt(suffix); if (suffix.equals(".jpg") || suffix.equals(".jpeg") || suffix.equals(".png") || suffix.equals(".gif")) { String fileName = uuid + suffix; pc.setNew_name(fileName); File targetFile = new File(strPath, fileName); if (!targetFile.getParentFile().exists()) { //注意,判断父级路径是否存在 targetFile.getParentFile().mkdirs(); } long size = 0; //保存 try { pictureFile.transferTo(targetFile); size = pictureFile.getSize(); } catch (Exception e) { e.printStackTrace(); }return pc; } else { /* JSONObject jsonObject = new JSONObject(); jsonObject.put("error", 1); */ return null; } } }}

图片实体类(省略service 和 Dao 层 文件):
package com.shangjian.cms.bean; import java.util.Date; /** * * @author Wangzhao * * 2019年4月28日-上午10:27:44 *图片实体类 */ public class Picture { private int id; //BIGINT(20)(NULL)NOPRI(NULL)AUTO_INCREMENTSELECT,INSERT,UPDATE,REFERENCES private Date addtime ; //DATETIME(NULL)YES(NULL)SELECT,INSERT,UPDATE,REFERENCES private int height ; //INT(50)(NULL)YES(NULL)SELECT,INSERT,UPDATE,REFERENCES private int width ; //INT(50)(NULL)YES(NULL)SELECT,INSERT,UPDATE,REFERENCES private String path ; //VARCHAR(100)utf8_general_ciYES(NULL)SELECT,INSERT,UPDATE,REFERENCES private String new_name; //VARCHAR(100)utf8_general_ciYES(NULL)SELECT,INSERT,UPDATE,REFERENCES private String old_name; //VARCHAR(100)utf8_general_ciYES(NULL)SELECT,INSERT,UPDATE,REFERENCES private String ext; //VARCHAR(50)utf8_general_ciYES(NULL)SELECT,INSERT,UPDATE,REFERENCES private float size ; //FLOAT(NULL)YES(NULL)SELECT,INSERT,UPDATE,REFERENCES public int getId() { return id; } public void setId(int id) { this.id = id; } public Date getAddtime() { return addtime; } public void setAddtime(Date addtime) { this.addtime = addtime; } public int getHeight() { return height; } public void setHeight(int height) { this.height = height; } public int getWidth() { return width; } public void setWidth(int width) { this.width = width; } public String getPath() { return path; } public void setPath(String path) { this.path = path; } public String getNew_name() { return new_name; } public void setNew_name(String new_name) { this.new_name = new_name; } public String getOld_name() { return old_name; } public void setOld_name(String old_name) { this.old_name = old_name; } public String getExt() { return ext; } public void setExt(String ext) { this.ext = ext; } public float getSize() { return size; } public void setSize(float size) { this.size = size; } }

Controller层添加对象,保存图片字段:
/** * form添加 * */ @ResponseBody @RequestMapping(value = https://www.it610.com/article/{"/formadd" }, method = RequestMethod.POST) public void formadd(HttpServletRequest request, HttpServletResponse response, @RequestParam("pictureFile") MultipartFile[] pictureFile, String at_tizhi, String at_txt,String title) throws Exception {// 处理图片组 // 接受保存图片的 ID List pcidList = new ArrayList(); if (pictureFile != null && pictureFile.length > 0) { for (int i = 0; i < pictureFile.length; i++) { MultipartFile file = pictureFile[i]; // 保存图片 Picture pc = new ImgToProjectTools().saveImgThree(file); int pc_id = picturemanagecontroller.addPicture(request, response, pc); pcidList.add(pc_id); } } // 构造对象 Aftercare_Tea at = new Aftercare_Tea(); at.setAt_tizhi(at_tizhi); at.setAt_txt(at_txt); at.setTitle(title); at.setPcids(StringUtils.strip(pcidList.toString(), "[]")); int mpa = iaftercare_teaservice.add(at); response.sendRedirect(request.getContextPath() + "/view/page/aftercare_tea/aftercare_teaList.jsp"); }

【JAVA 上传图片到 服务器(Tomcat)目录下】 如有疑问,请高人留言。。。。交流问题,及时回复。。

    推荐阅读