springboot(06)文件上传和下载

文件上传

springboot 文件上传(一)

package com.buba.controller;

import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/upload")
public class UploadController {

    // 单文件上传
    @RequestMapping("/upload2")
    public void upload(@RequestPart("headerImg") MultipartFile headerImg) throws IOException {
        if (!headerImg.isEmpty()) {
            // 获取上传文件的原始名称
            String originalFilename = headerImg.getOriginalFilename();
            // 设置上传文件的保存地址目录(存放在项目路径下)
            String dirPath = "D:\\img-test";
            // 设置上传后的文件名称(拼接)
            String newFileName = UUID.randomUUID() + "_" + originalFilename;
            headerImg.transferTo(new File(dirPath + "/" + newFileName));
        }
    }

//  多文件上传
    @RequestMapping("/upload1")
    public String upload1(@RequestPart("photos") MultipartFile[] photos) throws IOException {
        //上传文件路径
        String dirPath = "D:\\img-test";
        for (MultipartFile photo : photos) {
            photo.transferTo(
                    new File(dirPath + "/" +UUID.randomUUID() + "_" + photo.getOriginalFilename() ));
        }
        return "上传成功";
    }
}

这段代码是一个SpringBoot的Java类,用于文件上传和下载。其中包含两个上传文件的方法:

  1. upload方法用于单个文件上传。它使用@RequestMapping注解将请求映射到/upload/upload2路径。它使用@RequestPart注解来接收MultipartFile类型的上传文件,检查文件是否为空,获取上传文件的原始文件名,设置上传文件的保存地址目录,设置上传后的文件名称,最后将上传的文件保存到指定路径。
  2. upload1方法用于上传多个文件。它与upload方法的主要区别在于,它使用了MultipartFile[]类型的数组来接收多个上传文件,并且在循环中保存每个上传文件。

upload1方法中,首先设置了文件上传路径dirPath,然后遍历上传的文件数组photos,对于每个上传文件,生成一个唯一的新文件名,将上传的文件保存到指定路径dirPath下,最后返回"上传成功"的字符串。

@RequestMapping("/upload1")
    public String upload1(@RequestPart("photos") MultipartFile[] photos) throws IOException {
        //上传文件路径
        String dirPath = "D:\\img-test";
        for (MultipartFile photo : photos) {
            photo.transferTo(
                    new File(dirPath + "/" +UUID.randomUUID() + "_" + photo.getOriginalFilename()  ));
        }
        return "上传成功";
    }

springboot 文件上传(二)

首先,在pom.xml文件中添加以下commons-io依赖:

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

在Spring Boot中使用Apache Commons IO库来上传文件,可以使用FileUtils类的copyInputStreamToFile方法。以下是一个示例代码,它将上传文件保存到指定的目标文件中:

@RequestMapping(value = "/upload", method = RequestMethod.POST)
    public String handleFileUpload(@RequestParam("file") MultipartFile file) {
        //上传文件路径
        String dirPath = "D:\\img-test";
        if (!file.isEmpty()) {
            try {
                String fileName = file.getOriginalFilename();
                assert fileName != null;
                File destFile = new File(dirPath, fileName);
                FileUtils.copyInputStreamToFile(file.getInputStream(), destFile);
                return "上传成功";
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return "上传失败";
    }

在这个例子中,我们使用了@RequestParam注解来注入MultipartFile类型的文件对象。在handleFileUpload方法中,我们首先获取上传文件的原始文件名,然后创建一个目标文件对象destFile,将上传文件的输入流复制到目标文件中。如果上传成功,返回"上传成功"字符串;否则返回"上传失败"字符串。

文件下载

springboot用commons-io来下载文件(一)

首先,在pom.xml文件中添加以下commons-io依赖:

<!--文件下载-->
<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.6</version>
</dependency>
@RequestMapping("/download1")
    public ResponseEntity<byte[]> download1(HttpServletRequest request) throws Exception {
        String filename = "22227b813053-230b-4cdf-83f5-c1da61d6b2dd_新建文本文档.txt";
        // 确定要下载的文件路径
        String dirPath = "D:\\gitRepository\\springboot01";

        // 创建该文件对象(谷歌所用)
        File file = new File(dirPath + "/" + 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对象封装返回下载数据
        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");
    }

这是一个使用 Spring Boot 开发的文件下载功能。当用户请求该 /download1 地址时,会执行 download1 方法。

该方法中,首先定义要下载的文件名,然后获取该文件的路径并创建文件对象。接着,对文件名进行编码,防止中文乱码。然后设置响应头,通知浏览器以下载的方式打开文件,定义以流的方式下载返回文件的数据,将该对象读取时按字节传送。最终将下载数据使用 SpringMVC 框架的 ResponseEntity 对象封装返回。

其中,getFileName 方法是用于根据浏览器的不同进行编码设置,返回编码后的文件名。对于 IE 内核浏览器,统一为 UTF-8 编码显示,其它浏览器统一为 ISO-8859-1 编码显示。

springboot用commons-io来下载文件(二)

在Spring Boot中,我们可以使用Apache Commons IO库来下载文件。这个库提供了许多有用的方法来操作文件和流。

Maven依赖

首先,我们需要在pom.xml文件中添加以下Maven依赖:

<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.8.0</version>
</dependency>

下载文件

以下是一个简单的Spring Boot控制器方法,可以用来下载文件:

@GetMapping("/download")
public ResponseEntity<Resource> downloadFile() throws IOException {
    String filename = "example.txt";
    Resource resource = new ClassPathResource(filename);
    InputStream inputStream = resource.getInputStream();
    byte[] fileBytes = IOUtils.toByteArray(inputStream);
    HttpHeaders headers = new HttpHeaders();
    headers.add("Content-Disposition", "attachment; filename=" + filename);
    headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
    headers.add("Pragma", "no-cache");
    headers.add("Expires", "0");
    return ResponseEntity
            .ok()
            .headers(headers)
            .contentLength(fileBytes.length)
            .contentType(MediaType.parseMediaType("application/octet-stream"))
            .body(new ByteArrayResource(fileBytes));
}

在这个例子中,我们从类路径中加载一个文件,将其读入字节数组中,然后将其作为响应主体返回。我们还设置了一些响应头,以便浏览器能够正确地处理文件下载。

总结

使用Apache Commons IO库可以轻松地下载文件,在Spring Boot中实现文件下载变得非常容易。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

bilal-abdurehim

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值