SpringMVC的文件上传
程序员文章站
2022-06-03 08:52:49
...
浏览器发送上传文件请求给前端控制器,前端控制器找到文件解析器,文件解析器解析过后返还给前端控制器一个upload对象,再将这个对象传给Controller
前台代码:
<form method="post" enctype="multipart/form-data" action="controller/upload">
名称: <input type="text" name="picname"><br>
图片:<input type="file" name="upload"><br>
<input type="submit" value="上传">
</form>
注意一定要将method定为post
enctype一定要设为multipart/form-data
@RequestMapping("/upload")
public String testUpload(HttpServletRequest request, MultipartFile upload,String picname) throws IOException {
String fileName = "";
//获取原始文件名
String oldName = upload.getOriginalFilename();
//利用String API 中的subString(int beginIndex,int LastIndex)返回上传文件的后缀名
String suffix = oldName.substring(oldName.lastIndexOf(".") + 1, oldName.length());
//uuid方法生成随机名字
String uuid = UUID.randomUUID().toString().replace("-", "").toUpperCase();
//判断是否上传了图片名
if(!StringUtils.isEmpty(picname)){
fileName = uuid+"_"+picname+"."+suffix;
}
else {
fileName = uuid+"."+suffix;
}
System.out.println(fileName);
//获取项目部署的路径
String realPath = request.getSession().getServletContext().getRealPath("/upload/");
//初始化一个路径
File file = new File(realPath);
if(!file.exists()){
file.mkdirs();
}
upload.transferTo(new File(file,fileName));
return "success";
}
配置文件解析器
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize">
<!--设置图片最大上传大小为5MB-->
<value>5242880</value>
</property>
</bean>
注:id一定要是multipartResolver