[英]nodejs (using egg) return .zip file failed
我寫了一個 Nodejs 服務(使用 egg)來向瀏覽器返回一個 local.zip 文件(由一個目錄壓縮),但它失敗了。 代碼如下所示
雞蛋.js
// zip file by code or manually
async download() {
const ctx = this.ctx;
const params = ctx.request.body;
const downloadrepoName = params.fileName;
const filePath = path.resolve(__dirname, `../../public/${downloadrepoName}`);
// ctx.attachment(`${downloadrepoName}`);
const stats = fs.statSync(filePath);
ctx.response.set({
'Content-Type': 'application/octet-stream',
'Content-Disposition': `attachment; filename=${downloadrepoName}`,
'Content-Length': stats.size,
});
ctx.body = fs.createReadStream(filePath);
}
前台代碼
// ajax header
config.headers['responseType'] = 'blob'
config.headers['Accept'] = 'application/zip'
downloadFrontProject({ fileName }).then(res => {
// 使用插件,第二個參數是文件名
console.log(res)
const blob = new Blob([res])
const linkNode = document.createElement('a')
linkNode.download = fileName // a標簽的download屬性規定下載文件的名稱
linkNode.style.display = 'none'
linkNode.href = URL.createObjectURL(blob) // 生成一個Blob URL
document.body.appendChild(linkNode)
linkNode.click() // 模擬在按鈕上的一次鼠標單擊
URL.revokeObjectURL(linkNode.href) // 釋放URL 對象
document.body.removeChild(linkNode)
})
.zip 在服務上是 385k,但當我下載時是一個壞的 686k.zip
所有標題
此外,如果我返回一個.text文件,它工作正常。
作為節點初學者,需要一些幫助
import axios from 'axios'
const request = axios.create({
baseURL: process.env.VUE_APP_BASE_API_WX,
timeout: 10000
})
request({
url: '/api/frontscaffold/download',
method: 'post',
data: {
fileName: fileName
},
responseType: 'blob'
}).then((res) => {
console.log('res', res)
const blob = res.data
const reader = new FileReader()
reader.readAsDataURL(blob)
reader.onload = (e) => {
const a = document.createElement('a')
a.download = fileName
a.href = e.target.result
document.body.appendChild(a)
a.click()
document.body.removeChild(a)
}
})
當我像上面那樣寫的時候,一切正常......還是不明白
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.