KS3服务除了文件上传,储存数据使用比较频繁外,下载也同样比较常用。
本文就下载文件总结了以下几种的方式:
- 直接下载
// 该方式需要配置Content-Dispostion使用
// 先通过ks3-js-sdk生成分享外链, 此操作亦可更改为从应用服务器端获取外链
// 再通过浏览器直接下载文件
this.ks3.getObjectUrl({
key: file.Key // 文件的Key
}, function(err, data) {
if (err) {
console.log(err);
return;
}
window.open(data, '_self')
});
说明:
文件元信息
Content-Disposition如果PutObject或者PostObject时未设置,默认值None, 如果想使用浏览器端直接下载,需要在控制台将其设置为attachment,如果您想要直接在浏览器中预览文件,将Content-Disposition为inline即可。
- SDK下载
this.ks3.getObject({
key: file.Key
}, function (err, data) {
if (error) {
console.log(error)
return;
}
const reader = new FileReader()
reader.readAsDataURL(data.body)
reader.onload = function (e) {
const a = document.createElement('a')
a.download = 'download.log' // 文件名,按需求更改
a.href = e.target.result
document.documentElement.appendChild(a);
a.click()
a.remove()
}
})
- Ajax下载
this.ks3.getObjectUrl({
key: file.Key
}, function(err, data) {
if (err) {
console.log(err);
return;
}
const url = data
downloadFile(url).then(d => {
const reader = new FileReader()
reader.readAsDataURL(d)
reader.onload = function (e) {
const a = document.createElement('a')
a.download = 'download.log' // 文件名,按需求更改
a.href = e.target.result
document.documentElement.appendChild(a);
a.click()
a.remove()
}
}).catch(err => {
console.error('下载失败:', err)
})
});