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盘根目录下的文件

你可能感兴趣的:(Spring,Cloud,java)