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 # 单次请求的总文件大小上限
相关推荐
码事漫谈1 天前
AI正在攻破你的密码
后端
蜡笔小谢1 天前
DeepSeek Harness Java 实战笔记(五)|插件、MCP 与 Skill
java·笔记·ai·agent·deepseek·harness
皮皮林5511 天前
一款开源强大的数据同步神器,主流数据库全支持!
后端
唐老板1 天前
Spring AI 2.0 只支持 Boot 4
java
喵个咪1 天前
GoWind Trade(风帆):从询盘到收款的外贸全流程一体化平台
后端·架构·go
喵个咪1 天前
GoWind Ops:开箱即用的多节点运维平台——管机器、跑项目、发脚本、构建分发
后端·go·自动化运维
喵个咪1 天前
GoWind IM 私有化快速部署:研发型企业自己的协同底座
后端·架构·go
喵个咪1 天前
GoWind IoT(风行物联网):从设备接入到告警运维的设备管理平台
后端·物联网·go
我叫黑大帅1 天前
换尺寸、转个角度就认不出同一张图?让 16×16 灰度网格做感知去重
后端·面试·php
JavaGuide1 天前
刚刚,GLM-5.4 正式发布,实测来了:看图用 Blender 建凉亭、做技术视频,再画一辆真能传动的自行车
前端·后端