Java中利用SpringBoot框架实现文件下载功能

直接扔代码!!!!!!!!!!!!!!!!!!!!!!!!!!简单!!!!!!!!!!!!!!!!!!!

@RequestMapping(value = "/download", method = RequestMethod.GET)
    public void downloadFile(@RequestParam("fileName") String fileName, HttpServletResponse response) {
  //这里文件名称是通过参数传递过来的,要是不需要,直接可以写在这里。String fileName = "a.doc";
        String path = "C://";  //这里指定路径在C盘根目录,按需改动即可
        byte[] buffer = new byte[1024];
        FileInputStream fis = null;
        BufferedInputStream bis = null;
        try {
            File file = new File(path, fileName);
            response.setContentType("application/x-download");
            response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
            fis = new FileInputStream(file);
            bis = new BufferedInputStream(fis);
            OutputStream os = response.getOutputStream();
            int i = bis.read(buffer);
            while (i != -1) {
                os.write(buffer, 0, i);
                i = bis.read(buffer);
            }
        }catch(FileNotFoundException e) {
            e.printStackTrace();
            System.out.println("The file not found!");
     
        } catch (IOException e) {
            e.printStackTrace();
        } finally{
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

需要import的包如下

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import org.springframework.web.bind.annotation.*;

 

 

测试:浏览器输入 http://localhost:xxxx/download?fileName=a.doc

xxxx:后台程序的port

a.doc:C盘根目录下的文件

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值