①First download the FileSaver.js plug-in
npm install file-saver --save
②Introduce it into the required .vue page
import { saveAs } from 'file-saver'
Introduced in HTML
<script src="https://cdn.bootcdn.net/ajax/libs/FileSaver.js/2.0.5/FileSaver.min.js"></script>
//FileSaver.js只有一个函数就是saveAs,它有三个参数,
//第一个是:Blob、File、Url 可以是二进制流、文件、URL的地址。
//第二个是:文件的名字
//第三个是:可选的object对象。
// 示例
saveAs(参数一,参数二, 参数三)
③ If you want to save a TXT document locally
save(){
let blob = new Blob(["Hello, world!"], {type: "text/plain;charset=utf-8"});
saveAs(blob, "hello world.txt");
}
// "Hello, world!" 是文件的内容
// "hello world.txt" 是文件的名字
result:
content:
④ If you want to save a picture
save(){
saveAs('https://cube.elemecdn.com/6/94/4d3ea53c084bad6931a56d5158a48jpeg.jpeg', "image.jpg")
}
// 注意:通过URL保存图片时,存在阿里云服务端的图片必须设置为允许跨域,
// 因为在通过saveAs函数下载时,会请求一次这个地址,如果没设置,则会出现跨域问题。
result:
Picture content:
This will happen if the image is not allowed to cross domains:
⑤The following method can perfectly solve the cross-domain problem. It can not only download images but also PDF files and other files.
download() {
axios.post("/mth-finance-capital-service/api/common/download/file", {data:this.fileUrl}, {
headers: {"Content-Type": 'application/octet-stream'},
transformRequest: [function (data, headers) {
return data['data']
}],
responseType: 'blob'
}).then(response => {
// const contentType = response.headers['content-type']
// const blob = new Blob([response.data], {type: contentType})
// 这地方是前端进行的 blob转换,接口里面后端做了之后,我们就不需要再做了。
saveAs(response.data, this.fileUrlName)
// saveAs(blob, this.fileUrlName) 要是前端转换的话就用这个
}).catch(error => {
console.log("----",error)
// 处理错误
})
},
// 1. 直接发送axios请求,第一个是请求地址。
// 2. 第二个是图片或者其他文件的URL链接;这地方必须要用{}包起来,data是形参最好也加上。
// 3. headers: {"Content-Type": 'application/octet-stream'},请求头
// 4. transformRequest: [function (data, headers) { return data['data'] }],
// 表示允许在向服务器发送前,修改请求数据,data就是上面的形参。
// 5. responseType: 'blob' 后端返回的图片是二进制流的形式,所以要加这个。
// 6. this.fileUrlName 是文件的名字
⑥ The reason for adjusting the interface is to let the backend convert the URL of the image to be downloaded or the URL of other files into a blob type.
This is the response information in .then after the response is successful.
Finally call, saveAs(response.data, this.fileUrlName) to download.
⑦ Result: // The file name is the second parameter, I chose it randomly
Don’t worry about the result returned like this, just open the image in the file.
Picture after opening
⑧If the picture is damaged:
Please check whether responseType: 'blob' was included when sending the request, and whether the image link to be downloaded is wrapped in {}. Go back to step ⑤ to see.