Spring文件上传和下载

maven导包

<!-- 文件上传核心包  -->
<dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>1.3.3</version>
</dependency>
<!-- servlet核心包,servlet-api导入高版本的  -->
<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>4.0.1</version>
</dependency>

如果发布到tomcat,javax.servlet-api是3.0以上的版本,3.0以下的版本是servlet-api,那么如果tomcat的lib下没有得把包javax.servlet-api包,就要把包赋值到tomcat的lib下

Spring核心配置文件配置

<!-- 文件上传配置 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <!-- 请求的编码格式,必须和jsp的pageEncoding属性一致,以便正确读取表单的内容,默认为ISO-8809-i -->
    <property name="defaultEncoding" value="utf-8"/>
    <!-- 上传文件大小上限,单位为字节(10485760=10M) -->
    <property name="maxUploadSize" value="10485760" />
    <property name="maxInMemorySize" value="40960"/>
</bean>

 

接口

package com.lingaolu.controller;


import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.ServletContext;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;


/**
 * 【作者】 林高禄
 * 【描述】 文件控制层
 * 【时间】 2020/11/23 11:21
 **/
@RequestMapping("/file")
@RestController
public class FileController {

    @PostMapping(value = "/upload")
    public void chuMen(@RequestParam("file") CommonsMultipartFile file, HttpServletRequest request) throws IOException {
        //上传路径保存设置
        String path = request.getServletContext().getRealPath("/file");
        File realPath = new File(path);
        if(!realPath.exists()){
            realPath.mkdir();
        }
        file.transferTo(new File(realPath+"/"+file.getOriginalFilename()));
    }

    @GetMapping(value = "/download")
    public void chuMen(String fileName,HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 获取文件的MIME类型
        ServletContext servletContext = request.getServletContext();
        String mimeType = servletContext.getMimeType(fileName);
        // 获取文件的真实路径
        String realPath = servletContext.getRealPath("/file/" + fileName);
        // 将文件读入内存
        FileInputStream fis = new FileInputStream(realPath);
        // 设置相应头类型
        response.setHeader("content-type",mimeType);
        response.setHeader("content-disposition","attachment;filename="+fileName);
        // 将文件写出浏览器
        ServletOutputStream outputStream = response.getOutputStream();
        int len;
        byte[] by = new byte[1024*8];
        while((len = fis.read(by)) != -1){
            outputStream.write(by,0,len);
        }
        outputStream.close();
        fis.close();
    }

}

 

 

上一篇:使用response实现文件的下载


下一篇:文件下载