admin管理员组文章数量:1571361
浏览器下载文件在OSS存储,不需要将文件下载到本地,阿里云oss提供了相应api,返回文件的inputStream输入流
ossAPI
public class OSSTemplate {
// endpoint以杭州为例,其它region请按实际情况填写
String endpoint = "http://oss-cn-hangzhou.aliyuncs";
// accessKey请登录https://ak-console.aliyun/#/查看
String accessKeyId = "<yourAccessKeyId>";
String accessKeySecret = "<yourAccessKeySecret>";
String bucketName = "<yourBucketName>";
// 创建OSSClient实例
OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
public InputStream getFile(String filePath){
OSSObject ossObject = ossClient.getObject(bucketName, filePath);
InputStream in = ossObject.getObjectContent();
return in;
}
}
下载文件
public void getOSSFile(String filePath,HttpServletResponse response) {
InputStream in = null;
OutputStream out = null;
try {
String fileName = filePath.substring(filePath.lastIndexOf(File.separator) + 1);
response.setHeader("content-disposition","attachment;filename="+ URLEncoder.encode(fileName,"UTF-8"));//文件名如果包含中文需要指定编码
out = response.getOutputStream();
in = getFile(filePath);
byte[] data = new byte[1024];
int len = 0;
while ((len = in.read(data)) != -1) {
out.write(data, 0, len);
}
out.flush();
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
if (in != null) {
in.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if (out != null) {
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
浏览器下载
文件下载只支持get请求,而且不支持ajax,可以直接使用location
window.location.href = "http://example/download?filePaht=说明文档.doc";
版权声明:本文标题:浏览器下载阿里云OSS文件 内容由热心网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:https://www.elefans.com/dongtai/1726894993a1089056.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论