java web 下载文件

前端显示:

前端代码:

<a href="/api/download">Download</a>

后台使用的框架是springboot,代码如下:

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

@RestController
public class FileDownloadController {

    @RequestMapping(value = "/api/download")
    public String apply(HttpServletRequest request, HttpServletResponse response) {
        //被下载的文件在服务器中的路径,
        String downloadFilePath = "download/view.jpg";
        //被下载文件的名称,下载之后的文件显示的名字,
        可以用现在的view.jpg,也可以使用其它,比如:a.jpg
        String fileName = "Chrysanthemum.jpg";
         
        File file = new File(downloadFilePath);
         if (file.exists()) {
             // 设置强制下载不打开
            response.setContentType("application/force-download");
             response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);
             byte[] buffer = new byte[1024];
             FileInputStream fis = null;
             BufferedInputStream bis = null;
             try {
                 fis = new FileInputStream(file);
                 bis = new BufferedInputStream(fis);
                 OutputStream outputStream = response.getOutputStream();
                 int i = bis.read(buffer);
                 while (i != -1) {
                     outputStream.write(buffer, 0, i);
                     i = bis.read(buffer);
                 }
               
                 return "success";
             } catch (Exception 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();
                     }
                 }
             }
         }
        return "file doesn't found!";
    }
}

下载效果如下:

 

 

 

 

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值