FileDownLoadServlet 文件下载
package com.appdev.bsf.common.server.servlet;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class FileDownLoadServlet extends HttpServlet {
??? private static final long serialVersionUID = 1L;
??? @Override
??? protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException,
??? ??? ??? IOException {
??? ??? String path = request.getParameter("url");
??? ??? String[] paths = path.split("/");
??? ??? String fileName = paths[paths.length - 1];
??? ??? try {
??? ??? ??? String filePath = getServletContext().getRealPath(path);
??? ??? ??? InputStream inStream = new FileInputStream(filePath);// 文件的存放路径
??? ??? ??? // 设置输出的格式
??? ??? ??? response.reset();
??? ??? ??? response.setContentType("application/octet-stream");
??? ??? ??? response.addHeader("Content-Disposition",
??? ??? ??? ??? ??? "attachment; filename=" + new String(fileName.getBytes(), "ISO-8859-1"));
??? ??? ??? ServletOutputStream s = response.getOutputStream();
??? ??? ??? // 循环取出流中的数据
??? ??? ??? byte[] b = new byte[4096];
??? ??? ??? int len;
??? ??? ??? try {
??? ??? ??? ??? while ((len = inStream.read(b)) > 0) {
??? ??? ??? ??? ??? s.write(b, 0, len);
??? ??? ??? ??? }
??? ??? ??? ??? s.flush();
??? ??? ??? ??? s.close();
??? ??? ??? ??? inStream.close();
??? ??? ??? } catch (IOException e) {
??? ??? ??? ??? e.printStackTrace();
??? ??? ??? }
??? ??? } catch (Exception e) {
??? ??? ??? e.printStackTrace();
??? ??? ??? throw new IOException("系统出错!");
??? ??? }
??? }
}