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、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();
        }
    }
}
2.3、使用场景

在这里插入图片描述

3、下载zip文件

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

在这里插入图片描述

3.2、依赖
<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.11.0</version>
</dependency>
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();
        }
    }
}
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();
        }
    }
}
4.3、使用场景

在网盘软件中预览pdf文件

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值