Spring-MVC-文件上传下载

依赖

<dependency>
    <groupId>commons-fileuploadgroupId>
    <artifactId>commons-fileuploadartifactId>
    <version>1.3.3version>
dependency>
<dependency>
    <groupId>javax.servletgroupId>
    <artifactId>javax.servlet-apiartifactId>
    <version>4.0.1version>
dependency>

xml配置


<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    
    <property name="defaultEncoding" value="utf-8"/>
    
    <property name="maxUploadSize" value="10485760"/>
    <property name="maxInMemorySize" value="40960"/>
bean>

controller

@RestController
public class FileController {
    // 文件上传,从请求中读取文件路径
    @RequestMapping("/upload")
    // @RequestParam("file")会将name=file的控件上传的文件封装为CommonsMultipartFile对象,数组实现批量上传
    public String uploadFile(@RequestParam("file") CommonsMultipartFile file, HttpServletRequest request) throws IOException {
        String filename = file.getOriginalFilename();
        if ("".equals(filename)){
            return "redirect:/index.jsp";
        }
        // 上传路径保存设置
        String realPath = request.getServletContext().getRealPath("/upload");
        File realFile = new File(realPath);
        if (!realFile.exists()){
            realFile.mkdir();
        }
        // out/artifacts/SSM_war_exploded/uploadFile
        System.out.println(realFile);
        // 文件读写
        file.transferTo(new File(realFile + "/" + filename));
        return "redirect:/index.jsp";
    }
    // 文件下载,写入响应输出流
    @RequestMapping("/downLoad")
    public String downLoadFile(HttpServletRequest request, HttpServletResponse response) throws Exception {
        // 要下载的文件地址
        String realPath = request.getServletContext().getRealPath("/uploadFile");
        String fileName = "test.txt";
        // 设置响应头
        response.reset();// 清空缓存
        response.setCharacterEncoding("UTF-8");// 设置字符编码
        response.setContentType("multipart/form-data");// 二进制传输数据
        response.setHeader("Content-Disposition",
                "attachment;fileName=" + URLEncoder.encode(fileName,"UTF-8"));
        // 文件读写
        InputStream in = new FileInputStream(new File(realPath,fileName));
        OutputStream out = response.getOutputStream();
        int len = 0;
        byte[] buffer = new byte[1024];
        while ((len=in.read(buffer)) != -1){
            out.write(buffer,0,len);
            out.flush();
        }
        out.close();
        in.close();
        return "ok";
    }
}

你可能感兴趣的:(mvc)