使用Response实现文件下载

1.项目结构

使用Response实现文件下载_第1张图片

2.Servlet代码

package com.tls.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.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//文件下载
@WebServlet("/ResponseDemo3")
public class ResponseDemo3 extends HttpServlet {
	private static final long serialVersionUID = 1L;
       

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String path = this.getServletContext().getRealPath("/download/图片.jpg");
		String filename=path.substring(path.lastIndexOf("/")+1);
		System.out.println(filename);
		//如果下载的是中文文件名,则会乱码,需要使用url编码
		response.setHeader("Content-Disposition", "attachment; filename="+URLEncoder.encode(filename,"UTF-8"));
		InputStream in=null;
		OutputStream out=null;
		try {
			in=new FileInputStream(path);
			int len=0;
			byte buffer[]=new byte[1024];
			out=response.getOutputStream();
			while((len=in.read(buffer))!=-1){
				out.write(buffer,0,len);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			if(in!=null){
				in.close();
			}
		}
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}

你可能感兴趣的:(J2EE,Java)