java图片上传,通过MultipartFile方式,如果后台获取null检查是否缺少步骤

本方法基于springMvc

1.首先需要在webap下创建images

2.在springmvc.xml上引入


<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 最大允许上传大小5MB -->
<property name="maxUploadSize" value="5242880" />
<property name="maxInMemorySize" value="4096" />
<property name="defaultEncoding" value="UTF-8"></property>
</bean>

3.配置web.xml过滤器

4.后台代码

import org.springframework.web.multipart.MultipartFile;

@RequestMapping(value = "/uploadImg", method = RequestMethod.POST)
@ResponseBody
@ApiOperation(value = "图片上传", httpMethod = "POST", notes = "返回图片存放服务器路径")
public ReponseResult<String> uploadImg(@RequestParam(value="file",required=false)MultipartFile uploadFile,HttpServletRequest request) {
String imgurl=null;// 文件路径
String trueFileName=null;// 自定义的文件名称
if (uploadFile!=null) {// 判断上传的文件是否为空
String type=null;// 文件类型
String fileName=uploadFile.getOriginalFilename();// 文件原名称
System.out.println("上传的文件原名称:"+fileName);
// 判断文件类型
type=fileName.indexOf(".")!=-1?fileName.substring(fileName.lastIndexOf(".")+1, fileName.length()):null;
if (type!=null) {// 判断文件类型是否为空
if ("GIF".equals(type.toUpperCase())||"PNG".equals(type.toUpperCase())||"JPG".equals(type.toUpperCase())) {
// 项目在容器中实际发布运行的根路径
// String realPath="E:\apache-tomcat-8.5.40\apache-tomcat-8.5.40\webapps\imgs\";

//图片存放的路径,可写在本地硬盘,也可放在服务器上
//----------------------------本实例在服务器镜像映射的地址----------------------------------------------
String realPath="/usr/local/tomcat/webapps/项目名称/images/";


//自定义的文件名称
trueFileName=String.valueOf(System.currentTimeMillis())+fileName;
//设置存放图片文件的路径
imgurl=realPath+/*System.getProperty("file.separator")+*/trueFileName;
System.out.println("存放图片文件的路径:"+imgurl);
// 转存文件到指定的路径
try {
uploadFile.transferTo(new File(imgurl));
} catch (IllegalStateException e) {
logger.error(e.toString());
e.printStackTrace();
} catch (IOException e) {
logger.error(e.toString());
e.printStackTrace();
}
System.out.println("文件成功上传到指定目录下");
}else {
System.out.println("不是我们想要的文件类型,请按要求重新上传");
return ReponseResult.error(new CodeMsg(-1, "文件类型不符"));
}
}else {
System.out.println("文件类型为空");
return ReponseResult.error(new CodeMsg(-1, "文件类型为空"));
}
}else {
System.out.println("没有找到相对应的文件");
return ReponseResult.error(new CodeMsg(-1, "没有找到相对应的文件"));
}
//TODO 线上图片存放路径需要修改
//测试地址--------------------------------------------------------------------------
String returnUrl = "http://服务器地址/项目名称/images/"+trueFileName;
//测试地址--------------------------------------------------------------------------

return ReponseResult.success(returnUrl);
}

原文地址:https://www.cnblogs.com/guangxiang/p/11050946.html