java 下载另存为_java中如何实现点击下载出现另存为的对话框

本文介绍了如何在Java中实现点击下载功能,当用户点击时,浏览器会弹出'另存为'对话框。通过创建文件输入流,设置HttpServletResponse的响应头和类型,以及利用缓冲流进行文件传输,确保文件能够被正确下载。
摘要由CSDN通过智能技术生成

private void downValid(HttpServletResponse response,NetDiskFile netDiskFile)throws Exception{

try{

if(netDiskFile!=null){

File f = new File(netDiskFile.getAttach());

//文件流的输入

BufferedInputStream br = new BufferedInputStream(new FileInputStream(f));

response.reset();

response.setCharacterEncoding("gb2312");

response.setContentType("application/x-msdownload");

response.setHeader("Content-Disposition",

"attachment; filename="+this.toUtf8String(netDiskFile.getFilename())+"."+netDiskFile.getSuffix());

byte[] buf = new byte[1024];

int len = 0;

//文件流的输出

OutputStream output = response.getOutputStream();

while ((len = br.read(buf)) > 0){

output.write(buf, 0, len);

}

br.close();

output.close();

}else{

PrintWriter out=response.getWriter();

out.println("alert(\"you only can download the file, can't do the folder!\");history.back();");

}

}catch(FileNotFoundException e){

PrintWriter out=response.getWriter();

out.print("alert('Sorry,the file could not be found');history.back();");

}catch(Exception e){

PrintWriter out=response.getWriter();

out.print("alert('while downloading,the error happens.');history.back();");

}

}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值