您的位置:首页 > 其它

响应头Content-disposition,通知浏览器以附件形式去下载文件

2018-07-03 21:34 211 查看
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/chenzuen113113/article/details/80904721
1.Content-disposition响应头的作用:通知浏览器处理内容的方式以附件的形式下载。
2.在现实开发中很多时候我们都需要提供相应的功能给用户下载附件。比如:智联招聘(下载简历), 百度云(下载资料)
3.代码
代码:
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//需求: 向浏览器输出一张图片,然后通知浏览器以附件的形式处理。
public class ContentDispositionServlet extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//uuid可以保证产生的字符串是全球唯一的,  uuid是通过:cpu序列号+当前毫秒数算出的值。
String uuidFileName = UUID.randomUUID().toString();  //产生一个uuid

String fileName = uuidFileName+".jpg";
//对文件进行url编码
    //fileName = URLEncoder.encode(fileName, "utf-8");   // 解决了90%的浏览器, firefox浏览器解决不了。

//设置content-disposition响应头,通知浏览区以附件的形式下载处理。
response.setHeader("Content-Disposition", "attachment;filename="+fileName);

OutputStream out = response.getOutputStream();

//建立文件的输入流,读取本地的图片资源
FileInputStream fileInputStream = new FileInputStream("c:/pig/8.jpg");
//建立缓冲字节数组读取
byte[]  buf = new byte[1024];
int length = 0 ;
//不断的读取了图片的资源
while((length=fileInputStream.read(buf))!=-1){
//向浏览器输出
out.write(buf,0,length);
}
//关闭 资源
fileInputStream.close();

}

public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}

}

阅读更多
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐