1 前台传个文件的名称到后台
serivce 传值:<a href="<%=path%>/servletDownload?fileName="XXXXXXXX.dooc">
web.XML 设置:
ServletDownload 类中:
package com.ving.xzsp.touch.selfServ;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLDecoder;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ServletDownload extends HttpServlet{
private static final long serialVersionUID = 1L;
public ServletDownload() {
super();
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");//解决中文乱码
String fileName= request.getParameter("fileName");
//设置文件MIME类型
response.setContentType(getServletContext().getMimeType(fileName));
//设置Content-Disposition
response.addHeader("Content-Disposition","attachment;fileName="+URLDecoder.decode("Help.doc","UTF-8"));
//读取目标文件,通过response将目标文件写到客户端
//获取目标文件的绝对路径
String fullFileName = getServletContext().getRealPath("/download/" + fileName);
InputStream in = new FileInputStream(fullFileName);
OutputStream out = response.getOutputStream();
//写文件
int b;
while((b=in.read())!= -1)
{
out.write(b);
}
in.close();
out.close();
}
}