SpringMvc上传图片到本地,项目发到linux服务器也可以上传
代码
@RequestMapping(value = "/file/upload")
public Json uploadFile(String name,String dirUrl, MultipartFile file, HttpServletRequest request){
/* Map imageSize = sysBizParamsService.getBizParam("imageTotalSize");
long maxSize = Long.parseLong(imageSize.get("value").toString())*1024;
String[] suffixs = file.getOriginalFilename().split("\\.");
String suffix = suffixs[suffixs.length - 1];
Map ImageFormat = sysBizParamsService.getBizParam("ImageFormat");
String Remark = ImageFormat.get("Remark").toString();
if(Remark.contains(","+suffix+",")){
if(file.getSize() > maxSize){
throw new BizException("文件大小不能大于"+maxSize+"k");
}
}*/
String webappRoot =getRealPath(request.getServletContext(),"/");
File dir = new File(webappRoot+"/assets/uploads/"+dirUrl);
if(!dir.exists()){
dir.mkdirs();
}
String accessUrl = "/assets/uploads/"+dirUrl+'/'+System.currentTimeMillis()+name;
try {
File file1 = new File(webappRoot+accessUrl);
file.transferTo(file1);
} catch (IOException e) {
e.printStackTrace();
throw new BizException("上传失败");
}
Map map = new HashMap<>();
map.put("imageName",name);
map.put("accessUrl",accessUrl);
return json(map);
}
public String getRealPath(ServletContext ctx,String name) {
String realpath = ctx.getRealPath(name);
if (realpath == null) {
realpath = ctx.getRealPath("/") + name;
}
return realpath;
}
web.xml中加入配置
<!-- 配置静态资源 -->
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>/assets/*</url-pattern>
</servlet-mapping>