java后台简单从腾讯云下载文件通知前端以附件的形式保存

时间:2022-08-30 16:45:30

不废话 上代码

  // fileName :前台传入的文件名(主要是标识文件是什么格式.png或.zip)
// cosKey:上传文件时腾讯云返回的标识
// 配置腾讯云基本信息
String aliyunId = ApplicationPropertyUtils.getContextProperty("TENXUN_ACCESS_KEY_ID");
String aliyunSecret
= ApplicationPropertyUtils.getContextProperty("TENXUN_ACCESS_KEY_SECRET");
String ossEndpoint
= ApplicationPropertyUtils.getContextProperty("TENXUN_OSS_ENDPOINT");
COSClient cosClient
= new COSClient(cosEndpoint, tenxunId, tenxunSecret);


// 从腾讯云下载文件
GetObjectRequest getObjectRequest = new GetObjectRequest(bucketName,cosKey);//bucketName需要自己设置
COSObject cosObject = cosClient.getObject(getObjectRequest);
COSObjectInputStream cosObjectInput
= cosObject.getObjectContent();

// 从阿里云进行下载 http://blog.csdn.net/qq_35498405/article/details/77942817
// 缓冲文件输出流
BufferedOutputStream outputStream=new BufferedOutputStream(response.getOutputStream());
// 通知浏览器以附件形式下载
response.setHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode(fileName,"UTF-8"));

// 进行解码 为防止文件出现乱码 文件上传时进行编码处理
BASE64Decoder base64Decoder = new BASE64Decoder();

byte[] car=new byte[1024];
int L=0;
while((L=cosObjectInput.read(car))!=-1){
car
= base64Decoder.decodeBuffer(cosObjectInput);
//L 如果不给长度会有文件损坏
outputStream.write(car, 0,L);

}
if(outputStream!=null){
outputStream.flush();
outputStream.close();
}

}

注意:在实际使用该方法下载的过程中,可能遇到服务器不报错,但就是下载不下来文件的问题,这样有可能是前端页面发出下载请求的方式有误,不能使用AJAX的get方式访问该方法,因为Ajax能够返回的数据格式只能为html,script,json,xml,不接受流的形式。笔者使用的方式是用window.location.href访问,或者使用from表单提交方式(GET/POST)。

腾讯开放平台文档

https://cloud.tencent.com/document/product/436/10199#.E7.AE.80.E5.8D.95.E6.96.87.E4.BB.B6.E4.B8.8A.E4.BC.A0

阿里云下载链接

http://blog.csdn.net/qq_35498405/article/details/77942817