JavaWeb--文件下载
思路:
1.设置下载文件的格式
2.设置响应头(程序运行时,文件是自动打开还是弹出下载框;以什么形式下载;文件名(处理中文乱码))
3.获取文件的绝对路径
4.获取本地字节输入流
5.获取响应输出流
6.在循环中读写文件
package cn.kgc.cases;
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;
import java.io.FileInputStream;
import java.io.IOException;
@WebServlet("/download")
public class DownloadServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//定义一个变量给图片命名
String name="music";
//设置下载文件的格式
response.setContentType("video/mpeg");
//设置响应头:Content-Disposition使文件以下载框的形式弹出 attachment使文件以附件的形式下载 filename给文件命名 +后面的是处理文件名中文乱码
response.setHeader("Content-Disposition","attachment;filename="+java.net.URLEncoder.encode(name,"utf-8"));
//获取图片的绝对路径
String realPath = getServletContext().getRealPath("张信哲-爱如潮水.mp3");
//获取本地字节输入流读取图片
FileInputStream fis = new FileInputStream(realPath);
//获取response的输出流,向浏览器写图片
ServletOutputStream out = response.getOutputStream();
byte[]bytes=new byte[1024];
int len=0;
while((len=fis.read(bytes))!=-1){
out.write(bytes,0,len);
}
//关流
fis.close();
}
}