java项目开发-文件上传
作者:互联网
SpringMVC上传文件
1.前端页面设计
文件上传的控件是:,必须以POST方式提交表单,且必须配置enctype="multipart/form-data";
<form action="upload.do" method="post" enctype="multipart/form-data"> <input type="file" name="file"> <input type="submit"> </form>
2.添加依赖
基于commons-fileupload
3.在spring配置文件中添加配置:
配置CommonsMultipartReslover
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"></bean>
在这也可以配置其他属性,如long maxUploadSizePerFile :单个文件最大大小;long maxUploadSize:最大上传大小...
4.创建控制器处理上传
`@Controller
public class UploadController {
//处理上传功能请求的方法
@PostMapping("/upload.do")
@ResponseBody
public String handleUpload(HttpServletRequest request,@RequestParam("file") CommonsMultipartFile file) throws IllegalStateException, IOException {
boolean isEmpty = file.isEmpty();//判断上传文件是否为空
System.out.println(isEmpty);
//确定存储文件夹
String parsePath = request.getServletContext().getRealPath("upload");
File parse = new File(parsePath);
if (!parse.exists()) {
parse.mkdirs();
}
//确定获取的文件名
String originalFilename = file.getOriginalFilename();
//获取相关数据-文件大小
long size = file.getSize();
System.out.println("size:"+size);
String contentType = file.getContentType();
System.out.println("contentType:"+contentType);
List<String> allow = new ArrayList<String>();
allow.add("image/jpeg");
allow.add("image/png");
boolean isAllow=allow.contains(contentType);
//获取扩展名
int beginIndex = originalFilename.lastIndexOf(".");
String suffix = originalFilename.substring(beginIndex);
String fileName = System.currentTimeMillis()+suffix;
File dest = new File(parse, fileName);
**//保存文件**
file.transferTo(dest);
return "ok";
}
}`
转:https://blog.csdn.net/Shangxingya/article/details/109562739
标签:文件,contentType,String,System,parse,file,java,上传 来源: https://www.cnblogs.com/yuxuan1997love/p/16475676.html