package com.solaw.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.sun.image.codec.jpeg.ImageFormatException;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageDecoder;
public class DownloadFile extends HttpServlet {
private static final long serialVersionUID = 1L;
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String storePath = new String(request.getParameter(
"documentStorePath").getBytes("ISO-8859-1"), "utf-8").toString();
String fileFullName = storePath.substring(storePath
.lastIndexOf("/") + 1);
String filePath = new String(request.getParameter("documentStorePath")
.getBytes("ISO8859_1"), "utf-8").toString();
response.setContentType("text/html");
javax.servlet.ServletOutputStream out = response.getOutputStream();
System.out.println("DownloadFile filepath:" + storePath);
System.out.println("DownloadFile filename:" + fileFullName);
java.io.File file = new java.io.File(filePath);
if (!file.exists()) {
System.out.println(file.getAbsolutePath() + " 文件不存在!");
return;
}
// 读取文件流
java.io.FileInputStream fileInputStream = new java.io.FileInputStream(
file);
// 下载文件
// 设置响应头和下载保存的文件名
if (fileFullName != null && fileFullName.length() > 0) {
response.setContentType("application/x-msdownload");
response.setHeader("Content-Disposition", "attachment; filename="
+ new String(fileFullName.getBytes("utf-8"), "iso8859-1") + "");
if (fileInputStream != null) {
int filelen = fileInputStream.available();
// 文件太大时内存不能一次读出,要循环
byte a[] = new byte[filelen];
fileInputStream.read(a);
out.write(a);
}
fileInputStream.close();
out.close();
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<!DOCTYPE HTML PUBLIC -//W3C//DTD HTML 4.01 Transitional//EN>");
out.println("<HTML>");
out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>");
out.println(" <BODY>");
out.print(" This is ");
out.print(this.getClass().getName());
out.println(", using the POST method");
out.println("your hobby is:"+request.getParameter("hobby"));
out.println(" </BODY>");
out.println("</HTML>");
out.flush();
out.close();
}
}
同时web.xml需要配置
<servlet>
<servlet-name>DownloadFile</servlet-name>
<servlet-class>com.solaw.servlet.DownloadFile</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>DownloadFile</servlet-name>
<url-pattern>/vip/downloadDocument</url-pattern>
</servlet-mapping>