首页 > 代码库 > servlet文件下载

servlet文件下载

一、创建servlet

package com.demo.log4j;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class DownloadServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	public void init(ServletConfig config) throws ServletException {
	}

	public void doGet(HttpServletRequest req, HttpServletResponse response)
			throws IOException, ServletException {
		response.setContentType("text/plain");
		response.setHeader("Content-Disposition",
				"attachment; filename=demo.docx");
		OutputStream outputStream = response.getOutputStream();
		File file = new File("D:\\demo.docx");
		InputStream inputStream = null;
		try {
			inputStream = new FileInputStream(file);
			byte[] buffer = new byte[1024];
			int i = -1;
			while ((i = inputStream.read(buffer)) != -1) {
				outputStream.write(buffer, 0, i);
			}
			outputStream.flush();
			outputStream.close();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	public void doPost(HttpServletRequest req, HttpServletResponse res)
			throws IOException, ServletException {
	}

	public void destroy() {
	}
}

二、配置web.xml

<servlet>
	<servlet-name>download</servlet-name>
	<servlet-class>com.demo.log4j.DownloadServlet</servlet-class>
</servlet>
<servlet-mapping>
	<servlet-name>download</servlet-name>
	<url-pattern>/download</url-pattern>
</servlet-mapping>

三、下载文件

  浏览器访问地址

http://127.0.0.1:8080/download

servlet文件下载