下载的要求:
两个头一个流:
>Content-Type:传递给客户是什么HTML类型。例如 image/jpe
>Content-Disposition 他的默认值是 Inline 表示在浏览器窗口打开
---attachment(附件);filename=xxx(下载文件的名称)
JSP页面:
<body>
<form action="/Demo_file/xiazai1" method="post" enctype="multipart/form-data">
<input type="submit" value="下载">
</form>
</body>
Servlet:
import java.io.FileInputStream;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.IOUtils;
public class xiazai extends HttpServlet{
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String filename="D:\\demo.jpg";
String contentType=this.getServletContext().getMimeType(filename);//通过文件获取文件属相
String contentDisposition="attachment;filename=a.jpg";
resp.setHeader("Content-Type", contentType);
resp.setHeader("Content-Disposition", contentDisposition);
//将文件放入这个输入流中
FileInputStream in = new FileInputStream(filename);
ServletOutputStream out =resp.getOutputStream();
IOUtils.copy(in, out);
in.close();
}
}