文件下载(java版)

//文件下载
package com.xxx.file;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
@WebServlet("/file/download")
public class downloadApi extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //寻找服务器中需要下载的文件名
        String filename="服务器中文件名.jpg";
        //按照当前字符编码进行打散
        byte[] bytes=filename.getBytes("utf-8");
        //将目标字符进行组装
        String outfilename=new String(bytes,"ISO8859-1");
        //设置响应头,outfilename即下载到客户端后的文件名
        resp.setHeader("content-disposition","attachment;filename="+outfilename);
        //在文件夹中寻找需要下载的文件
        InputStream is=this.getServletContext().getResourceAsStream("/images/需要下载的文件名.jpg");
        //创建输出流
        ServletOutputStream os=resp.getOutputStream();
        int len=-1;
        byte[] buf=new byte[1024];
        while ((len=is.read(buf))!=-1){
            os.write(buf,0,len);
        }
        //关闭输入流和输出流
        os.close();
        is.close();
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

注意:使用文件上传和文件下载时都需要引用一下两个坐标

<dependency>
      <groupId>commons-io</groupId>
      <artifactId>commons-io</artifactId>
      <version>2.6</version>
</dependency>
<dependency>
      <groupId>commons-fileupload</groupId>
      <artifactId>commons-fileupload</artifactId>
      <version>1.4</version>
</dependency>
posted @   Lcode_mask  阅读(64)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
点击右上角即可分享
微信分享提示