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 # 单次请求的总文件大小上限
相关推荐
junnhwan2 小时前
LeetCode Hot 100——栈
java·数据结构·算法·leetcode·hot 100
蓝天星空2 小时前
C# .net闭源与Java开源框架的对比
java·c#·.net
金牌归来发现妻女流落街头2 小时前
【用 Java API Client 操作 Elasticsearch】
java·elasticsearch·jenkins
Seven972 小时前
调试排错 - 线程Dump分析
java
Z...........2 小时前
Spring日志管理
java·后端·spring
lj850862 小时前
性能测试总结
java·开发语言·spring
yhdata2 小时前
自然灾害检测物联网系统市场稳步扩容:2032年规模剑指392.7亿元,六年CAGR达33.8%
java·物联网·struts
小锅锅氩2 小时前
JavaDay01
java·ide·intellij-idea
smxgn2 小时前
Springboot 整合 Quartz(定时任务框架)
java·spring boot·后端