SpringBoot实现文件上传和下载

java 复制代码
 // 文件上传和下载 multipartfile byte数组获取比特流
    @PostMapping("/upload")
    public String handleFileUpload(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return "Please select a file to upload.";
        }
        try {
            byte[] bytes = file.getBytes();
            String uploadDir = "D:\\project\\wms\\web002-main\\wms001\\file_upload_download\\";
            File uploadedFile = new File(uploadDir + file.getOriginalFilename());
            file.transferTo(uploadedFile);
            return "File uploaded successfully!";
        } catch (IOException e) {
            e.printStackTrace();
            return "File upload failed!";
        }
    }
    // 上传/下载的根目录(建议和上传接口保持一致,可从配置文件注入)
    private static final String UPLOAD_DIR = "D:\\project\\wms\\web002-main\\wms001\\file_upload_download\\";
    /**
     * 文件下载接口
     * @param fileName 要下载的文件名(前端传入,需和上传时的文件名一致)
     * @return 响应体(包含文件流)
     */
    @GetMapping("/download")
    public ResponseEntity<byte[]> downloadFile(@RequestParam("fileName") String fileName) {
        // 1. 构建要下载的文件完整路径
        File downloadFile = new File(UPLOAD_DIR, fileName);

        // 2. 校验文件是否存在
        if (!downloadFile.exists()) {
            // 返回 404 状态码 + 提示信息
            return ResponseEntity.status(HttpStatus.NOT_FOUND)
                    .body(("文件不存在:" + fileName .getBytes(StandardCharsets.UTF_8)).getBytes());
        }

        // 3. 读取文件字节流
        try (InputStream inputStream = new FileInputStream(downloadFile)) {
            // 读取文件到字节数组
            byte[] fileBytes = new byte[(int) downloadFile.length()];
            inputStream.read(fileBytes);

            // 4. 设置响应头(关键:处理中文文件名、指定下载类型)
            HttpHeaders headers = new HttpHeaders();
            // 处理中文文件名乱码(URLEncoder 编码)
            String encodedFileName = URLEncoder.encode(fileName, StandardCharsets.UTF_8).replace("+", "%20");
            // 设置响应头:指定文件下载方式、文件名
            headers.add("Content-Disposition", "attachment; filename=\"" + encodedFileName + "\"");
            // 设置响应媒体类型(二进制流,支持所有文件类型)
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            // 设置文件大小
            headers.setContentLength(fileBytes.length);

            // 5. 返回响应(200 成功 + 响应头 + 文件字节流)
            return new ResponseEntity<>(fileBytes, headers, HttpStatus.OK);

        } catch (IOException e) {
            e.printStackTrace();
            // 返回 500 状态码 + 错误信息
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(("文件读取失败:" + e.getMessage()).getBytes(StandardCharsets.UTF_8));
        }
    }

yml配置

XML 复制代码
server:
  port: 8090

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/wms
    driver-class-name: com.mysql.cj.jdbc.Driver
    username: root
    password: 123456
  servlet:
    multipart:
      max-file-size: 10MB    # 单个文件的最大大小
      max-request-size: 10MB # 单次请求的总文件大小上限
相关推荐
2601_962071572 小时前
【Java报错已解决】org.springframework.beans.factory.BeanCreationException
java·开发语言
zww89491112 小时前
酒馆预约系统开发实战:从需求分析到上线全流程指南
java·eclipse
东风破_4 小时前
从跨域到 WebSocket:前端跨域方案、SSE 与双向实时通信详解
前端·后端
zww89491115 小时前
匿名树洞系统开发实战:从需求分析到部署指南
java·eclipse
行百里er5 小时前
Gateway 上别硬塞 MVC:DeferredImportSelector 看菜下锅
spring boot·后端·开源
名字还没想好☜5 小时前
Java 遍历时删元素抛 ConcurrentModificationException:fail-fast 原理与三种正确删法
后端
IT_陈寒6 小时前
React Hooks闭包陷阱差点让我加班到凌晨
前端·人工智能·后端
黑马程序员毕设6 小时前
基于Java的医院药品管理系统的优化设计与实现
java·开发语言·spring boot·小程序·架构·课程设计·毕设
木井巳6 小时前
【BFS/DFS 解决 FloodFill 算法】太平洋大西洋水流问题
java·算法·leetcode·深度优先·广度优先·宽度优先·推荐算法
码事漫谈7 小时前
本体论,彻底懂
后端