Springboot使用ResponseEntity进行简单的上传和下载文件

本文档展示了如何使用SpringBoot实现文件上传和下载功能。通过创建`FileDealController`,定义了`upload`和`download`两个方法,分别处理文件上传到指定路径和从路径下载文件。上传时,文件会被保存到`E:Tour`目录下,而下载时,文件以附件形式提供,并确保中文文件名正确显示。测试可以通过Postman进行上传验证,以及在浏览器中输入URL下载文件。
摘要由CSDN通过智能技术生成

springboot上传下载文件

创建controller层

@RestController
public class FileDealController {

   /**
   上传文件的方法,将文件上传到某个存在的位置
   @param file 文件名
   */
    @PostMapping("/upload")
    public void upload(@RequestParam("file")MultipartFile file)throws Exception{
    // 这里由于逻辑较多所以封装了一个util
        fileUtil.upload(file);
    }
    /**
   下载文件的方法,将文件从某个存在的位置上下载下来
   @param filename 文件名
   */
    @GetMapping("/download")
    public ResponseEntity download(@RequestParam("filename")String filename) throws Exception{
    //指定预下载文件的位置
        FileSystemResource file = new FileSystemResource("E:\\Tour\\"+filename);
        HttpHeaders httpHeaders = new HttpHeaders();
        //指定下载后的文件名等,new String(filename.getBytes("UTF-8"),"ISO8859-1")很重要,不然会下载中文名的时候名字为空
        httpHeaders.add("Content-Disposition","attachment; filename="+new String(filename.getBytes("UTF-8"),"ISO8859-1"));
        return ResponseEntity.ok()
                .headers(httpHeaders)
                .contentLength(file.contentLength())
                .contentType(MediaType.parseMediaType("application/octet-stream"))
                .body(new InputStreamResource(file.getInputStream()));
    }


}

上传使用的util

import org.apache.commons.lang3.StringUtils;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;

public class fileUtil {

    /**
     * @param names 文件下文件名的集合
     * @param name  存入的文件名
     * @param index 索引的开始位置
     * @return 符合要求的文件名
     */
    private static String checkFileName(ArrayList<String> names, String name, int index) {
        String indexName;
        if (index == 0 ) {
            indexName = name;
        } else {
            indexName = name.substring(0, name.indexOf(".")) + "(" + index + ")" +name.substring(name.indexOf("."));
        }
        if (names.contains(indexName)) {
            index +=1;
            name = checkFileName(names, name, index);
        } else {
            return indexName;
        }
        return name;
    }
    /**
     * @param path 需要遍历的路径
     * @return 路径下文件的名称集合
     */
    private static ArrayList<String> getFile(String path) {
        // 获得指定文件对象
        File file = new File(path);
        // 获得该文件夹内的所有文件
        File[] array = file.listFiles();
        ArrayList<String> list = new ArrayList<>();
        if (array != null) {
            for (File value : array) {
                list.add(value.getName());
            }
        }
        return list;
    }
    public static void upload(MultipartFile file) throws IOException {
    //上传路径
        String uploadPath = "E:\\Tour\\";
        ArrayList<String> list = getFile(uploadPath);
        /*获取文件名*/
        String getFileName = file.getOriginalFilename();
        String fileName;
        //查询是否重名,重名角标加一
        fileName = checkFileName(list, getFileName,0);
        String filePath =uploadPath + fileName;
        BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(filePath));
        outputStream.write(file.getBytes());
        outputStream.flush();
        outputStream.close();
    }
}

测试

测试上传

  1. 使用postman测试上传
    在这里插入图片描述
    2.去指定路径的文件夹下查看结果
    在这里插入图片描述

测试下载

在浏览器输入http://localhost:8086/download?filename=nginx-1.18.0.zip进行下载

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
实现文件上传下载功能,可以借助 Spring Boot 和 MyBatis 框架提供的丰富的 API。下面是一个简单的示例代码: 文件上传: ```java @PostMapping("/upload") public String uploadFile(@RequestParam("file") MultipartFile file) { if (file.isEmpty()) { return "上传文件为空"; } try { byte[] bytes = file.getBytes(); Path path = Paths.get("uploads/" + file.getOriginalFilename()); Files.write(path, bytes); } catch (IOException e) { e.printStackTrace(); } return "文件上传成功"; } ``` 文件下载: ```java @GetMapping("/download") public ResponseEntity<byte[]> downloadFile() throws IOException { Path path = Paths.get("uploads/example.txt"); byte[] bytes = Files.readAllBytes(path); HttpHeaders headers = new HttpHeaders(); headers.add("Content-Disposition", "attachment; filename=example.txt"); ResponseEntity<byte[]> responseEntity = new ResponseEntity<>(bytes, headers, HttpStatus.OK); return responseEntity; } ``` 在这个示例中,我们使用Spring Boot 提供的 @PostMapping 和 @GetMapping 注解来处理文件上传下载请求,使用了 MyBatis 框架来实现文件上传下载所需的持久化操作。 为了更好地组织代码,我们可以将文件上传下载的逻辑封装成 Service 层的方法,然后在 Controller 中调用这些方法。同时,我们也可以使用 Spring Boot 提供的更加便捷的配置来实现文件上传下载,例如通过配置文件设置上传文件大小限制,设置上传文件路径等。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值