java 下载功能_java 下载功能的实现

在jsp中有一个a标签 ,当用户点击a标签的时候下载文件。

我们采用href属性直接指向一个服务器地址,只要链接的文件存在,就会给出弹出保存对话框.

点击a标签 先执行onclick事件,再请求href中指向的地址。

前端jsp:

然后在js中:

function downloadtest(id){

var url = "/app/download" + "/" + id;

$("#pluginurl").attr("href",url);

}

后台java代码: 我的是springmvc

/**

* 下载文件

* @param id appid

* @param response

*/

@RequestMapping(value="/download/{id}")

publicvoiddownload(@PathVariableString id, HttpServletResponse response){

String filepath = "";

Result result = appService.getAppById(id);

App app = (App) result.getMap().get("app");

if(app ==null){

return;

}

filepath = app.getUrl();

File file = newFile(filepath);

InputStream inputStream = null;

OutputStream outputStream = null;

byte[] b=newbyte[1024];

intlen =0;

try{

inputStream = newFileInputStream(file);

outputStream = response.getOutputStream();

response.setContentType("application/force-download");

String filename = file.getName();

filename = filename.substring(36, filename.length());

response.addHeader("Content-Disposition","p_w_upload; filename="+ URLEncoder.encode(filename,"UTF-8"));

response.setContentLength( (int) file.length( ) );

while((len = inputStream.read(b)) != -1){

outputStream.write(b, 0, len);

}

} catch(Exception e) {

e.printStackTrace();

}finally{

if(inputStream !=null){

try{

inputStream.close();

inputStream = null;

} catch(IOException e) {

e.printStackTrace();

}

}

if(outputStream !=null){

try{

outputStream.close();

outputStream = null;

} catch(IOException e) {

e.printStackTrace();

}

}

}

}

注意:response.addHeader("Content-Disposition","p_w_upload; filename=" + URLEncoder.encode(filename, "UTF-8"));

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值