首页 > 其他 > 详细

文件下载

时间:2020-01-31 17:01:46      阅读:51      评论:0      收藏:0      [点我收藏+]

1.通过浏览器下载文件

1)新建一个springboot的项目test,

2)新建文件下载的类Download

package com.example.demo1214.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

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

/**
 * @Author: yushizhong
 * @Date: 2020/1/31 14:51
 * @Title: 描述
 */
@Controller
public class Download {

    @GetMapping("/download")
    public void doenload(String filename, HttpServletRequest request, HttpServletResponse response ) throws IOException {
        //filename文件的名称,这里方便测试使用的是同一个名称,实际中可使用uuid
        //文件的路径
        String path="C:\\Users\\钟玉石\\Downloads";
        File file=new File(path+File.separator+filename);
        if(!file.exists()){
            response.setContentType("text/html;charset=UTF-8");
            response.getWriter().write("error");
            return;
        }else{
            //设置浏览器直接下载文件,不打开,并设置文件名的编码
            response.setHeader("content-disposition","attachment;filename="+ URLEncoder.encode(filename,"UTF-8"));
            //把数据给浏览器
            FileInputStream in=new FileInputStream(file);
            int len=0;
            byte bytes[]=new byte[1024];
            OutputStream out=response.getOutputStream();
            while ((len=in.read(bytes))>0){
                out.write(bytes,0,len);
            }
            in.close();
        }
    }
}

3)在static目录下新建文件下载页面

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <a href="/download?filename=报告.doc">下载</a>
</body>
</html>

4)测试。

启动项目,在浏览器输入http://localhost:8080/file.html,点击下载即可下载对应的文件。

文件下载

原文:https://www.cnblogs.com/zys2019/p/12245606.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!