package shiyao.frist.test.文件下载;
import java.io.FileInputStream;
import java.io.IOException;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
Servlet implementation class FileDownLoad
*/
@WebServlet("/FileDownLoad")
public class FileDownLoad extends HttpServlet {
private static final long serialVersionUID = 1L;
@see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.getWriter().append("Served at: ").append(request.getContextPath());
//1.获取文件请求参数,也就是文件名称
String Filename=request.getParameter("Filename");
//2.获取文件的服务器路径即真实路径
ServletContext sc=this.getServletContext();
String path=sc.getRealPath("/img/"+Filename);
//3.将文件和相关的流关联起来
FileInputStream fis=new FileInputStream(path);
//为了解决输入流已经被调用的情况
response.reset();
//为了解决文件名是中文的问题:使用DownLoadUtils工具类
//获取User-Agent请求头得知浏览器种类
String user_agent=request.getHeader("user-agent");
Filename=DownLoadUtils.getFileName(user_agent, Filename);
//4.设置响应头
//4.1设置content-type
String mimeType=sc.getMimeType(Filename);
response.setHeader("content-type", mimeType);
//4.2设置响应头打开方式:content-disposition为附件打开方式
response.setHeader("content-disposition","attachment;filename="+Filename);
//5将输入流的数据读出到输出流中
ServletOutputStream sos=response.getOutputStream();
byte[] buff=new byte[1024*8];
int len=0;
while((len=fis.read(buff))!=-1)
{
sos.write(buff,0,len);
}
fis.close();
}
}
这里只有一个getOutputStream没有getWrite为什么也报getWriter() has already been called for this response错误?
response.getWriter().append("Served at: ").append(request.getContextPath());
ServletOutputStream sos=response.getOutputStream();
......第一条是debug吧....用日志输出不行么.....
你眼神要好点了...
哈哈忘记了,这是模板自带的