Java教程

javaweb文件下载操作

本文主要是介绍javaweb文件下载操作,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
package top.spirit.servlet;

import javax.servlet.ServletContext;
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.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;

public class ServletDemo06 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1、获取下载文件的路径
        String realPath = this.getServletContext().getRealPath("/WEB-INF/classes/中文.png");
        System.out.println(realPath);
        //2、设置文件下载名
        String fileName = realPath.substring(realPath.lastIndexOf("\\")+1);
        //3、设置浏览器下载头
        resp.setHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode(fileName,"utf-8"));
        //4、获取下载文件的输入流
        FileInputStream in = new FileInputStream(realPath);
        //5、创建缓冲区
        int len = 0;
        byte[] buffer = new byte[1024];
        //6、获取OutputString对象
        ServletOutputStream out = resp.getOutputStream();
        //7、将FileOutputStream写入到buffer缓冲区,使用OutputStream将缓冲区数据输出到客户端
        while((len=in.read(buffer))>0){
            out.write(buffer,0,len);
        }
        out.close();
        in.close();
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
这篇关于javaweb文件下载操作的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!