文件上传
1 单文件上传
- 步骤1:环境搭建,拷贝jar包
-
步骤2:环境搭建,编写配置类
@Bean public CommonsMultipartResolver multipartResolver(){ CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(); // 设置所有的上传文件的总大小 10M multipartResolver.setMaxInMemorySize(10*1024*1024); // 设置单个文件上传的大小 4M multipartResolver.setMaxUploadSize(4*1024*1024); multipartResolver.setDefaultEncoding("utf-8"); return multipartResolver; }
-
步骤3:编写表单
<form action="${pageContext.request.contextPath}/file/upload.action" method="post" enctype="multipart/form-data"> 选择文件: <input type="file" name="image" /> <br/> <input type="submit" value="上传"/> <br/> </form>
-
步骤4:编写处理类
package com.czxy.mvcanno.controller; import org.apache.commons.io.FileUtils; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.multipart.MultipartFile; import java.io.File; import java.io.IOException; /** * @author 桐叔 * @email liangtong@itcast.cn */ @Controller @RequestMapping("/file") public class FileController { @RequestMapping("/upload") public String upload(MultipartFile image) throws Exception { System.out.println("上传文件名:" + image.getOriginalFilename()); System.out.println("上传文件流:" + image.getInputStream()); File file = new File("D:\\xml", image.getOriginalFilename()); FileUtils.copyInputStreamToFile(image.getInputStream(), file ); return "book"; } }
2.文件上传
2.1 多文件上传
-
表单
<form action="${pageContext.request.contextPath}/file/upload2.action" method="post" enctype="multipart/form-data"> 选择文件: <input type="file" name="images" /> <br/> 选择文件: <input type="file" name="images" /> <br/> 选择文件: <input type="file" name="images" /> <br/> <input type="submit" value="上传"/> <br/> </form>
-
控制器
@RequestMapping("/upload2") public String upload2(List<MultipartFile> images) throws Exception { for (MultipartFile image : images) { System.out.println("上传文件名:" + image.getOriginalFilename()); System.out.println("上传文件流:" + image.getInputStream()); File file = new File("D:\\xml", image.getOriginalFilename()); FileUtils.copyInputStreamToFile(image.getInputStream(), file ); } return "book"; }