spring mvc/Java web 文件上传
Java web文件上传
Java 的原生文件上传其实比较简单
分为前端和后端两块
前端
<form role="form" enctype="multipart/form-data" action="">
这个enctype
改成multipart/form这个是前端需要做的部分
后端
导入一些包
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
配置一个servlet
public String addBook(HttpServletRequest request) throws Exception {
String fileName = "";
//上传的位置
String path = request.getSession().getServletContext().getRealPath("/imgs/");
//判断该路径是否存在
File file = new File(path);
if (!file.exists()) {
file.mkdirs();
}
//解析request对象
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List<FileItem> items = upload.parseRequest(request);
//构建一个map存储变量
Map<String,Object> map = new HashMap<>();
//遍历
for (FileItem item : items) {
if (item.isFormField()) {
//普通表单
String fieldName = item.getFieldName();
String string = item.getString();
//处理编码问题
String s = new String(string.getBytes("iso-8859-1"),"UTF-8");
map.put(fieldName,s);
} else {
//上传文件项
String filename = item.getName();
//防止上传非图片文件
if (filename.contains(".png")||filename.contains(".jpg")) {
String uuid = UUID.randomUUID().toString().replace("-", "");
String saveName = uuid + "_" + filename.substring(filename.lastIndexOf(File.separator) + 1);
fileName = saveName;
item.write(new File(path, saveName));
map.put("pic", fileName);
//删除临时文件
item.delete();
}
}
}
bookService.addBook(map);
String view = "forward:/management/modify/"+map.get("id");
return view;
}
核心就是
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List<FileItem> items = upload.parseRequest(request);
然后通过io流的方式进行输出到磁盘中
通过spring mvc上传
在配置文件中配置
<!--配置MultipartResolver,用于文件上传-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!--上传文件大小上限-->
<property name="maxInMemorySize" value="5000000"/>
<!--请求编码格式-->
<property name="defaultEncoding" value="UTF-8"/>
</bean>
编写Controller
@Controller
public class FileUploadController {
private static String UPLOAD_DIRECTORY = PropertiesUtil.get("fileupload.directory", "");
@RequestMapping(value = "uploadFile", method = RequestMethod.POST)
public ModelAndView uploadFile(@RequestParam("file") MultipartFile file){
// 判断文件是否为空
if (!file.isEmpty()) {
try {
//判断文件目录是否存在,否则自动生成
File directory = new File(UPLOAD_DIRECTORY);
if (!directory.exists()){
directory.mkdirs();
}
//失败跳转视图
if (file.getSize() > 30000)
return new ModelAndView("uploadFail","msg",file.getOriginalFilename()+"超过了指定大小");
// 文件保存路径
String filePath = FilenameUtils.concat(UPLOAD_DIRECTORY, file.getOriginalFilename());
// 转存文件
file.transferTo(new File(filePath));
} catch (Exception e) {
e.printStackTrace();
}
}
//成功跳转视图
return new ModelAndView("uploadSuccess","msg",file.getOriginalFilename());
}
}
还能更方便
@RequestMapping("/upload")
public String upload(@RequestParam("file") MultipartFile file, HttpServletRequest req)throws IllegalStateException, IOException {
// 判断文件是否为空,空则返回失败页面
if (file.isEmpty()) {
return "failed";
}
// 获取文件存储路径(绝对路径)
String path = req.getServletContext().getRealPath("/WEB-INF/file");
// 获取原文件名
String fileName = file.getOriginalFilename();
// 创建文件实例
File filePath = new File(path, fileName);
// 如果文件目录不存在,创建目录
if (!filePath.getParentFile().exists()) {
filePath.getParentFile().mkdirs();
System.out.println("创建目录" + filePath);
}
// 写入文件
file.transferTo(filePath);
return "success";
}
使用file.transferTo(filePath);
直接完成向磁盘中写入