文件下载的实现步骤
将content-type设置为文件的内容类型,即设置MIME类型
添加一个Content-Disposition的响应首部字段,赋值为attachment;filename=filename
如果文件名带有中文,需要进行编码
使用输出流对文件进行输出
package com.ls.javaees1;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
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;
@WebServlet("/download")
public class Servlet2 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setHeader("content-type", "application/ocelet-stream");
response.addHeader("Content-Disposition", "attachment;filename=示例.rar");
ServletOutputStream os=response.getOutputStream();
FileInputStream is=new FileInputStream(new File("c://demo.rar"));
byte[] data=new byte[2048];
int len=0;
while((len=is.read(data, 0, data.length))!=-1){
os.write(data, 0, len);
}
os.close();
is.close();
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}