Java Web程序上传阿里云后图片出错问题总结
上传图片错误应该很多人都遇到过吧,像这种500的错很难找,今天就总结一下!
前提:在windows系统上能够上传图片,项目部署后无法上传。
原因1,tomcat创建文件权限不足
首先我们进入linux的系统的tomcat环境 cd /opt/tomcat/bin
在这下面找到catalina.sh 并编辑它 vi catalina.sh
在编辑界面找到这句话
if [ -z "$UMASK" ]; then
UMASK="0027"
fi
umask $UMASK
并将0027改为0022,或者0000都行,0000赋予更高的权限。
然后保存重启tomcat即可生效。
错误二:就是我犯的错误!路径错误!原因是写代码的时候自己太懒了,上传文件搜了一个如下图:
@RequestMapping("/editProduct.do")
public String editProductAndInfo(String pid,String productname,double price,Integer pnum,
String category,String description,MultipartFile imgurl,
HttpSession session,Model model) throws IllegalStateException, IOException {
Products products = productService.getProductById(pid);
products.setName(productname);
products.setCategory(category);
products.setDescription(description);
products.setPnum(pnum);
products.setPrice(price);
products.setProductid(pid);
if (!imgurl.isEmpty()) {
String randomName = FileUploadUtils.generateRandonFileName(imgurl.getName());
String uploadPath = session.getServletContext().getRealPath("/");
String filepath = uploadPath+"productImg\\upload\\"; //这里错了
String originalname = imgurl.getOriginalFilename();
String newFileName = IdUtils.getUUID()+originalname;
File targetfile = new File(filepath,newFileName);
if (!targetfile.exists()) {
targetfile.mkdir();
}
imgurl.transferTo(targetfile);
products.setImgurl("/productImg/upload/"+newFileName);
Productinfo productinfo = new Productinfo();
productinfo.setProductid(products.getProductid());
productinfo.setKeyword(products.getCategory());
productinfo.setSaletime(new Date());
productinfo.setUserid(user.getUserid());
productService.addProduct(products);
}
productService.updateProduct(products);
return "admin/edit_success";
}
可以看到windows下路径是反斜杠,但是到linux系统下就行不通了,改成正斜杠即可。
正确代码如下:
@RequestMapping("/editProduct.do")
public String editProductAndInfo(String pid,String productname,double price,Integer pnum,
String category,String description,MultipartFile imgurl,
HttpSession session,Model model) throws IllegalStateException, IOException {
Products products = productService.getProductById(pid);
products.setName(productname);
products.setCategory(category);
products.setDescription(description);
products.setPnum(pnum);
products.setPrice(price);
products.setProductid(pid);
if (!imgurl.isEmpty()) {
//随机名称
String randomName = FileUploadUtils.generateRandonFileName(imgurl.getName());
String uploadPath = session.getServletContext().getRealPath("/");
String filepath = uploadPath+"productImg/upload";
//获取图片扩展名
String originalname = imgurl.getOriginalFilename();
//获取新文件的文件名
String newFileName = IdUtils.getUUID()+originalname;
File targetfile = new File(filepath,newFileName);
if (!targetfile.exists()) {
targetfile.mkdir();
}
imgurl.transferTo(targetfile);
products.setImgurl("/productImg/upload/"+newFileName);
}
productService.updateProduct(products);
return "admin/edit_success";
}