Springboot 文件下载接口开发

本文详细介绍如何在SpringBoot中实现文件下载接口,包括具体实现思路、代码示例及测试方法。通过添加FileUtils类中的文件下载函数和FileResource类中的download函数,配合FileDownloadController控制器,轻松完成文件下载功能。

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

Springboot 文件下载接口开发

具体思路

之前做了有关文件上传到服务器的相关工作,与之对应必然有人需要从服务器进行文件的下载操作,这里沿着上一阶段的路线接着做文件下载的相关操作。

实现

由于实体类在之前已经定义好了所以不再进行重复定义,FileUtils类里面需要添加一个函数

public static void filedownload(OutputStream os,String filepath){
        BufferedInputStream bis = null;
        try {
            bis = new BufferedInputStream(new FileInputStream(new File(filepath)));
            byte[] buff = new byte[1024];
            int i = bis.read(buff);
            while (i != -1) {
                os.write(buff, 0, i);
                os.flush();
                i = bis.read(buff);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        System.out.println(" download success");
    }

此外,对应的FileResource类里面添加对应的dowload函数

public String Download(HttpServletResponse res,int fileId) throws IOException {

        FileResource fr = filePathRepository.findById(fileId).get();
        String fileName =fr.getFilename();
        res.setHeader("content-type", "application/octet-stream");
        res.setContentType("application/octet-stream");
        res.setHeader("Content-Disposition", "attachment;filename=" + fileName);
        FileUtil.filedownload(res.getOutputStream(),fr.getPath());
        return "succes dowload";

    }

新建一个FileDownloadController

import com.example.login.service.FileResourceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


@Controller
public class FileUploadController {

    @Autowired
    private FileResourceService filePathService;
    @RequestMapping("/download")
    @ResponseBody
    public String downloadFile(@RequestParam("fileId") int fileId ,HttpServletResponse res) throws IOException {
        return filePathService.Download(res,fileId);
    }
}

测试方式如下由于postman对于接受的数据所展示的格式太少,经常会乱码,所以可以选择在浏览器输入这样的地址
http://localhost:8181/download?fileId=(对应文件id)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值