springboot-文件上传与下载

该博客介绍了如何使用SpringBoot进行文件上传和下载的实现。配置了YML文件设置上传路径,编写了Controller来处理文件上传、文件列表查询、文件下载和文件删除操作。示例代码展示了具体的实现细节。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

使用spring initializr初始化一个springboot项目

在这里插入图片描述

先编写yml配置文件,设置文件上传路径

server:
  ip: localhost
  port: 8000

#spting:
#  servlet:
#    multipart:
#      # 开启上传和下载
#      enabled: true
#      # 最大的文件大小
#      max-file-size: 2000MB
#      # 单次最大请求大小
#      max-request-size: 2000MB

files:
  upload:
    path: E:/file/h/uplods/

编写Controller

package com.song.boot.file;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.configurationprocessor.json.JSONException;
import org.springframework.boot.configurationprocessor.json.JSONObject;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Arrays;


@RestController
public class FileController {
    
    @Value("${files.upload.path}")
    private String filesUploadPath;

    @PostMapping("/file")
    public String filesUpload(@RequestParam MultipartFile file) throws IOException, JSONException {
        JSONObject result = new JSONObject();
        if (file.isEmpty()) {
            result.put("error", "空文件");
            return result.toString();
        }
        String fileName = file.getOriginalFilename();
        String prefix = fileName.substring(0, fileName.lastIndexOf("."));
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        //检测目录是否存在
        String filePath = filesUploadPath + fileName;
        File fileTemObj = new File(filePath);
        if (!fileTemObj.getParentFile().exists()) {
            fileTemObj.getParentFile().mkdirs();

        }
        
        //检测文件是否已存在
        if (fileTemObj.exists()) {
            int count = 1;
            File file1 ;
            while (true) {
                file1 = new File(filesUploadPath + prefix + "-" + count + suffix);
                if (file1.exists()) {
                    count++;
                } else {
                    break;
                }
            }
            fileTemObj = file1;
        }
        //写入文件
        file.transferTo(fileTemObj);
        return "success,filePath:" + fileTemObj.getAbsolutePath();
    }

    @GetMapping("/file/list")
    public String queryFile() {
        File file = new File(filesUploadPath);
        return Arrays.toString(file.list());
    }

    @GetMapping("/file/{filename}")
    public String fileDownload(@PathVariable("filename") String filename, HttpServletResponse response) throws IOException, JSONException {
        JSONObject result = new JSONObject();
        File file = new File(filesUploadPath + "/" + filename);
        if (!file.exists()) {
            result.put("error", "文件不存在!");
            return result.toString();
        }
        //设置输出流格式
        response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
        response.setContentType("application/octet-stream");
        ServletOutputStream outputStream = response.getOutputStream();

        byte[] bytes = FileCopyUtils.copyToByteArray(file);
        outputStream.write(bytes);
        return "success";
    }

    @DeleteMapping("/file")
    public String deleteFile(@RequestParam("filename") String filename) {
        File file = new File(filesUploadPath + "/" + filename);
        if (!file.exists()) {
            return "文件不存在!";
        } else {
            if (file.delete()) {
                return "文件已删除";
            }
            return "删除失败";
        }
    }

    @GetMapping("/test/{name}")
    public String names(@PathVariable("name") String name) {
        return name;
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值