注册 X
我已阅读并同意  服务条款
首页 > IT技术笔记 > 查看笔记

java后台返回文件流下载文件

前端html请求:

                <a href="" id="filedownload" ></a>

<script type="text/javascript">

     let url = '/indexController/getFileOutputStream?path='+param;

     $("#filedownload").attr("href",url);

     document.getElementById("filedownload").click();

</script>


java后端代码:

@RequestMapping("/getFileOutputStream")

public void getFileOutputStream(HttpServletResponse response,String path) {

response.setCharacterEncoding("UTF-8");

OutputStream out = null;

System.out.println(path);


System.out.println("==========getFileOutputStream=========文件路径:"+path);

        File file = new File(path);    //1、建立连接

        BufferedInputStream is = null;

        byte[] b = new  byte[4096];

        int len = 1024;

        // 清空response

        response.reset();

        response.setContentType("application/x-download");//设置response内容的类型 普通下载类型


try {

response.setHeader("Content-disposition","attachment;filename="+ URLEncoder.encode(file.getName(), "UTF-8"));//设置头部信息

out = response.getOutputStream();

is = new BufferedInputStream(new FileInputStream(file));

while((len= is.read(b)) != -1) {

out.write(b,0,len);

}


} catch (Exception e) {

e.printStackTrace();

}finally {

try {

out.flush();

if(is!=null)

is.close();

if(out!=null)

out.close();

} catch (IOException e) {

e.printStackTrace();

}

}

}



 打赏        分享



评论