下载
下载就是向客户端响应字节数据
把一个文件转换成字节数组
然后使用response.getOutputStream来响应给浏览器
下载的要求
两个头一个流
1.Content-Type: 传递给客户端的文件是什么mime类型 比如image/pjpeg
2.Content-Disposition: 默认值是inline,表示在浏览器窗口中打开
如果想要弹框,就使用attachment;filename=xxx
3.stream: 要下载的文件的数据
public class DownServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//路径
String path = "f:/test/andy.jpg";
//获取mimeType类型
String mimeType = getServletContext().getMimeType(path);
//ContentDisposition内容意向
String contentDisposition = "attachment;filename=andy.jpg";
//获取文件输入流
FileInputStream inputStream = new FileInputStream(path);
//设置头
resp.setHeader("Content-Type", mimeType);
resp.setHeader("Content-Disposition", contentDisposition);
//得到输出流对象
ServletOutputStream outputStream = resp.getOutputStream();
//把输入流中的数据写入到输出流中
IOUtils.copy(inputStream, outputStream);
//关闭流
inputStream.close();
}
}
<servlet>
<servlet-name>downServlet</servlet-name>
<servlet-class>servlet.DownServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>downServlet</servlet-name>
<url-pattern>/down</url-pattern>
</servlet-mapping>
现在我们输入/down 的时候,会自动进行下载
我们在网络上下载东西的时候
绝大多数情况下,文件名都是英文名
这是为了防止中文的文件名出现乱码的情况
所以大多数人都会取英文名字
那么如果我们要取一个中文名
怎么防止出现乱码的情况呢
来点代码
String filename="F:/七里香.mp3";
String newfilename=new String(filename.getBytes("GBK),"ISO-8859-1");
这样就行了