Upload and download of SpringBoot (nine) files

1. File upload

It can be tested through the form form. The MultipartFile object is requested through the file type of the form form and is the value obtained through the name value of the form.

It can also be tested through swagger, access path: http://127.0.0.1:8081/swagger-ui.html#/

<form th:action="@{/upload}" method="post" enctype="multipart/form-data">
    头像:<input type="file" name="headerImg"><br>
    <input type="submit" value="上传">
</form>
@RestController
public class UploadController {
    // 文件上传 RequestMapping默认get请求
    @PostMapping("/upload")
    //MultipartFile对象是通过form表单的file类型请求的,是通过表单的name值获取的value值,也可以通过swagger测试
    public void upload(MultipartFile headerImg) throws IOException {
        // 单文件上传
        if (!headerImg.isEmpty()) {
            // 获取上传文件的原始名称,获取上传的文件的文件名 x.xxx(1.jpg)
            String originalFilename = headerImg.getOriginalFilename();
            // 设置上传文件的保存地址目录(存放在项目路径下)
            String dirPath = "E:\\Movie";
​
            // 字符串截取后缀名
//            String suffix = uploadFile.getOriginalFilename().substring(uploadFile.getOriginalFilename().lastIndexOf('.'));
​
            // 设置上传后的文件名称(拼接)  //获取uuid ,随机生成一个名字
            String newFileName = UUID.randomUUID() + "_" + originalFilename;
​
            //File.separator:自动匹配路径的分隔符(在不确定路径的分隔符是\还是/的时候可以使用)
            //上传文件
            headerImg.transferTo(new File(dirPath + File.separator + newFileName));
        }
    }
}

1. If you want to upload large files, you must configure the yml file

spring:
  #配置上传文件大小设置
  servlet:
    multipart:
      enabled: true
      max-file-size: 10MB  #单个文件的最大上限
      max-request-size: 30MB #单个请求的文件总大小上限

2. File download

1. Add dependencies

<!--文件下载 io流依赖-->
<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.6</version>
</dependency>

2. Test

The first:

You can pass the a tag test to customize the image to be downloaded, but you must select the file in the String dirPath = "E:\Movie"; directory,

It can also be tested through swagger, access path: http://127.0.0.1:8081/swagger-ui.html#/

<a th:href="@{/download(filenanem=1.jpg)}">下载图片</a>
@RestController
public class DownController {
    @GetMapping("/download")
    public ResponseEntity<byte[]> download1(HttpServletRequest request, String filename) throws Exception {
​
        // 确定要下载的文件路径
        String dirPath = "E:\\Movie";
​
        // 创建该文件对象(谷歌所用) //File.separator:自动匹配路径的分隔符(在不确定路径的分隔符是\还是/的时候可以使用)
        File file = new File(dirPath + File.separator + filename);
        System.out.println(file);
​
        //对文件名编码,防止中文乱码
        filename = this.getFileName(request,filename);
​
        // 设置响应头
        HttpHeaders headers = new HttpHeaders();
        // 通知浏览器以下载的方式打开文件
        headers.setContentDispositionFormData("attachment", filename);
        // 定义以流的方式下载返回文件的数据
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        // 将该对象读取时按字节传送,响应体
        byte[] array = FileUtils.readFileToByteArray(file);
        // 使用SpringMVC框架的ResponseEntity对象封装返回下载数据  HttpStatus.OK:响应状态码
        ResponseEntity<byte[]> responseEntity = new ResponseEntity<>(array, headers, HttpStatus.OK);
        return responseEntity;
    }
​
    /**
     * 根据浏览器的不同进行编码设置,返回编码后的文件名
     */
    public String getFileName(HttpServletRequest request, String filename) throws Exception {
        //IE不同版本User-Agent中出现的各种关键词
        String[] IEBrowserKeyWords = {"MSIE", "Trident", "Edge"};
        //获取请求头代理信息
        String userAgent = request.getHeader("User-Agent");
        for (String keyWord : IEBrowserKeyWords) {
            if (userAgent.contains(keyWord)) {
                //IE内核浏览器,统一为UTF-8编码显示
                return URLEncoder.encode(filename, "UTF-8");
            }
        }
        //其它浏览器统一为ISO-8859-1编码显示
        return new String(filename.getBytes("UTF-8"), "ISO-8859-1");
    }
}

The second type:

The file to be downloaded can be customized and uploaded through the form form, but the file must be uploaded in the directory specified by String dirPath = "E:\Movie"; before downloading

The MultipartFile object is requested through the file type of the form form, and is the value obtained through the name value of the form

It can also be tested through swagger, access path: http://127.0.0.1:8081/swagger-ui.html#/

<form th:action="@{/download2}" method="post" enctype="multipart/form-data">
    文件:<input type="file" name="headerImg"><br>
    <input type="submit" value="上传要下载的文件">
</form>
@RestController
public class DownController2 {
​
    //第二种下载文件:通过form表单可以自定义下载要下载的文件,但必须在dirPath指定的目录下上传文件在下载
    @PostMapping("/download2")
    public ResponseEntity<byte[]> download1(HttpServletRequest request, MultipartFile headerImg) throws Exception {
​
        // 确定要下载的文件路径
        String dirPath = "E:\\Movie";
​
        // 选取想要下载的文件,获取选中的文件的文件名 x.xxx(1.jpg)
        String originalFilename = headerImg.getOriginalFilename();
        String name = headerImg.getName();
        System.out.println("getName():"+name);
​
        // isEmpty() 判断是否为空,或者上传的文件是否有内容
        if(!originalFilename.isEmpty()){
            // 创建该文件对象(谷歌所用)
            File file = new File(dirPath + File.separator + originalFilename);
            System.out.println(file);
            //对文件名编码,防止中文乱码
            originalFilename = this.getFileName(request,originalFilename);
​
            // 设置响应头
            HttpHeaders headers = new HttpHeaders();
            // 通知浏览器以下载的方式打开文件
            headers.setContentDispositionFormData("attachment", originalFilename);
            // 定义以流的方式下载返回文件的数据
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            // 将该对象读取时按字节传送,响应体
            byte[] array = FileUtils.readFileToByteArray(file);
            // 使用SpringMVC框架的ResponseEntity对象封装返回下载数据  HttpStatus.OK:响应状态码
            ResponseEntity<byte[]> responseEntity = new ResponseEntity<>(array, headers, HttpStatus.OK);
            return responseEntity;
        }
​
        return null;
​
    }
​
    /**
     * 根据浏览器的不同进行编码设置,返回编码后的文件名
     */
    public String getFileName(HttpServletRequest request, String filename) throws Exception {
        //IE不同版本User-Agent中出现的各种关键词
        String[] IEBrowserKeyWords = {"MSIE", "Trident", "Edge"};
        //获取请求头代理信息
        String userAgent = request.getHeader("User-Agent");
        for (String keyWord : IEBrowserKeyWords) {
            if (userAgent.contains(keyWord)) {
                //IE内核浏览器,统一为UTF-8编码显示
                return URLEncoder.encode(filename, "UTF-8");
            }
        }
        //其它浏览器统一为ISO-8859-1编码显示
        return new String(filename.getBytes("UTF-8"), "ISO-8859-1");
    }
}

Guess you like

Origin blog.csdn.net/m0_65992672/article/details/130421621