• Java编程技巧:文件上传、下载、预览


    1、上传文件

    1.1、代码
    @PostMapping("/uploadFile")
    public String uploadFile(MultipartFile file) {
        System.out.println("文件名称:" + file.getOriginalFilename());
        return "成功";
    }
    
    @PostMapping("/uploadFile2")
    public String uploadFile2(
            @RequestParam("file") MultipartFile file
    ) {
        System.out.println("文件名称:" + file.getOriginalFilename());
        return "成功";
    }
    
    @PostMapping("/uploadFile3")
    public String uploadFile3(
            @RequestPart("file") MultipartFile file
    ) {
        System.out.println("文件名称:" + file.getOriginalFilename());
        return "成功";
    }
    
    // 发送文件的同时带上参数
    @PostMapping("/uploadFile4")
    public String uploadFile4(
            @RequestPart("file") MultipartFile file, // 可以换成“MultipartFile file”或者“@RequestParam("file") MultipartFile file”
            @RequestParam("id") String id
    ) {
        System.out.println("文件名称:" + file.getOriginalFilename());
        System.out.println("id:" + id);
        return "成功";
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    1.2、postman测试截图

    在这里插入图片描述

    1.3、拓展

    上面讲述的都是上传单个文件,不过也可以同时上传多个文件,写法如下:

    在这里插入图片描述

    2、下载resources目录中的模板文件

    2.1、项目结构

    假设resources目录下有一个pdf文件:用户数据导入模板.xlsx,然后我们来下载该文件

    在这里插入图片描述

    2.2、代码
    import org.apache.tomcat.util.http.fileupload.IOUtils;
    import org.springframework.core.io.ClassPathResource;
    import org.springframework.core.io.Resource;
    import org.springframework.http.MediaType;
    import org.springframework.http.MediaTypeFactory;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.RestController;
    import javax.servlet.ServletOutputStream;
    import javax.servlet.http.HttpServletResponse;
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.io.UnsupportedEncodingException;
    
    @RestController
    public class TestController {
    
    	@GetMapping("/downloadLocalFile")
        public void downloadLocalFile(HttpServletResponse response) throws IOException {
            String fileName = "用户数据导入模板.xlsx";
            Resource r = new ClassPathResource(fileName);
            try (
                    FileInputStream fileInputStream = new FileInputStream(r.getFile());
                    ServletOutputStream outputStream = response.getOutputStream();
            ) {
                response.setContentType("application/force-download");
                try {
                    fileName = new String(fileName.getBytes("utf-8"), "ISO-8859-1");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
                IOUtils.copyLarge(fileInputStream, outputStream);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    2.3、使用场景

    在这里插入图片描述

    3、下载zip文件

    3.1、等待被复制的文件夹(实际项目中这肯定是大家自己组装目录结构)

    在这里插入图片描述

    3.2、依赖
    <dependency>
        <groupId>commons-io</groupId>
        <artifactId>commons-io</artifactId>
        <version>2.11.0</version>
    </dependency>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    3.3、代码
    import org.apache.tomcat.util.http.fileupload.IOUtils;
    import org.springframework.web.bind.annotation.GetMapping;
    import javax.servlet.ServletOutputStream;
    import javax.servlet.http.HttpServletResponse;
    import java.io.*;
    import java.util.ArrayList;
    import java.util.List;
    import java.util.zip.ZipEntry;
    import java.util.zip.ZipOutputStream;
    
    public class TestController {
        @GetMapping("/downloadZip")
        public void downloadZip(HttpServletResponse response) {
            // 组装数据
            /**
             * 导出结果:
             * 文章
             *      测试文章.docx
             *      视频
             *          测试视频.mp4
             * 测试图片.jpg
             */
            byte[] data = null;
            try (
                    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                    ZipOutputStream zip = new ZipOutputStream(outputStream);
            ) {
                List<String> filePaths = new ArrayList<>();
                filePaths.add("文章" + File.separator + "测试文章.docx");
                filePaths.add("文章" + File.separator + "视频" + File.separator + "测试视频.mp4");
                filePaths.add("测试图片.jpg");
                for (String filePath : filePaths) {
                    try (
                            // 本次使用本次资源,所以添加了目录前缀:C:/test/20230930/,大家也可以换成其他流,比如从minio获取的流
                            InputStream in = new FileInputStream("C:/test/20230930/" + filePath)
                    ) {
                        zip.putNextEntry(new ZipEntry(filePath));
                        IOUtils.copyLarge(in, zip);
                        zip.closeEntry();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                data = outputStream.toByteArray();
            } catch (Exception e) {
                e.printStackTrace();
            }
    
            // 导出zip
            String fileName = "批量导出.zip";
            try (
                    ServletOutputStream outputStream = response.getOutputStream();
            ) {
                response.setContentType("application/force-download");
                try {
                    fileName = new String(fileName.getBytes("utf-8"), "ISO-8859-1");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
                org.apache.commons.io.IOUtils.write(data, outputStream);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    3.4、结果

    下面是导出的zip文件解压之后的结果:

    在这里插入图片描述

    4、预览文件

    4.1、项目结构

    resources下面的文件为例,展示预览文件的代码,这是从本地获取文件,当然也可以通过其他方式获取文件

    在这里插入图片描述

    4.2、代码
    import org.apache.tomcat.util.http.fileupload.IOUtils;
    import org.springframework.core.io.ClassPathResource;
    import org.springframework.core.io.Resource;
    import org.springframework.http.MediaType;
    import org.springframework.http.MediaTypeFactory;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.RestController;
    import javax.servlet.ServletOutputStream;
    import javax.servlet.http.HttpServletResponse;
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.io.UnsupportedEncodingException;
    
    @RestController
    public class TestController {
    
    	@GetMapping("/previewLocalFile")
        public void previewLocalFile(HttpServletResponse response) throws IOException {
            String fileName = "SQL必知必会(第5版).pdf";
            Resource r = new ClassPathResource(fileName);
            try (
                    FileInputStream fileInputStream = new FileInputStream(r.getFile());
                    ServletOutputStream outputStream = response.getOutputStream();
            ) {
                // 区别点1:将“response.setContentType("application/force-download");”替换成下面内容
                response.setContentType(MediaTypeFactory.getMediaType(fileName).orElse(MediaType.APPLICATION_OCTET_STREAM).toString());
                try {
                    fileName = new String(fileName.getBytes("utf-8"), "ISO-8859-1");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                // 区别点2:预览是“filename”,下载是“attachment;filename=”
                response.setHeader("Content-Disposition", "filename=" + fileName);
                IOUtils.copyLarge(fileInputStream, outputStream);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    4.3、使用场景

    在网盘软件中预览pdf文件

  • 相关阅读:
    Android Jetpack之LiveData源码分析
    学习WiFi,怎么入手?
    C++设计模式之装饰者模式(结构型模式)
    java之mybatis语法
    Apache Linkis参数介绍
    vue+springboot+websocket实时聊天通讯功能
    SSM篇目录总结
    大型电商网站的异步多级缓存及nginx数据本地化动态渲染架构
    Unity实现简易太阳系
    Linux文件/目录高级管理二
  • 原文地址:https://blog.csdn.net/qq_42449963/article/details/133419546