使用response实现文件的下载

Posted 离落想AC

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用response实现文件的下载相关的知识,希望对你有一定的参考价值。

注意中文文件名的处理。

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class Responsedown
 */
public class Responsedown extends HttpServlet 
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Responsedown() 
        super();
        // TODO Auto-generated constructor stub
    

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
		// TODO Auto-generated method stub
		//response.getWriter().append("Served at: ").append(request.getContextPath());
	       down(request,response);
	

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
		// TODO Auto-generated method stub
		doGet(request, response);
	
	
	private void down(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
		
		String filePath = getServletContext().getRealPath("拜托了世界.mp3");
		
		String filename = "歌曲拜托了世界.mp3";
		
		response.setHeader("Content-Disposition", "attachment;filename="+URLEncoder.encode(filename,"UTF-8"));
		
		response.setHeader("Content-Type", "application/octet-stream");
		InputStream in = new FileInputStream(filePath);
		OutputStream out = response.getOutputStream();
		int len = -1;
		byte b[] = new byte[1024];
		while((len=in.read(b))!=-1)
			out.write(b, 0, len);
		
		in.close();
		out.close();
	

浏览器访问: http://localhost:8888/MyJspProject/Responsedown


下载完成。

Eclipse 运行

以上是关于使用response实现文件的下载的主要内容,如果未能解决你的问题,请参考以下文章

response没有实现跳转,而是提示浏览器下载文件

python使用response下载txt文件到本地

[javaEE] response实现图片下载

asp.net 怎么实现pdf下载功能

HttpServletResponse对象实现文件下载

HttpServletResponse对象实现文件下载