Reputation: 21
I made the ability to download files. The code works well on PC web browsers but not on mobile web browsers. I would appreciate it if you know how it works on mobile.
const filePath = findFile[0].path;
const fileName = findFile[0].filename;
const mimetype = mime.getType(filePath);
// Header setting
res.setHeader('fileName', encodeURIComponent(fileName));
res.setHeader('Content-type', mimetype);
res.setHeader('Content-Disposition', 'attachment; filename=' + encodeURIComponent(fileName));
// aws s3 file
const params = {
Bucket: 'flag-kog',
Key: `${username}/${fileName}`
};
s3.getObject(params)
.createReadStream()
.pipe(res);
componentDidMount() {
const {
username,
flagname
} = this.props.match.params;
axios({
url: `/api/files/download/${username}/${flagname}`,
method: 'GET',
responseType: 'blob',
})
.then(res => {
const filename = decodeURIComponent(res.headers.filename);
this.setState({
filename,
});
// Download
const url = window.URL.createObjectURL(new Blob([res.data]));
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', filename);
document.body.appendChild(link);
link.click();
this.setState({
downloading: true,
});
})
.catch(() =>
this.setState({
err: true,
})
);
}
Upvotes: 2
Views: 715
Reputation: 31
Try it once!! it works.
• For Example: If you want to download images or files on click by 'download' link.
(by onClick prevent jquery)
HTML code: where your input code place.
<a><img src="XYZ" /></a>
<p>file name</p>
<a href="XYZ" @click.prevent="_downloadImg('{{downLoad}}','file name')">Download</a>
Jquery code:
_downloadImg(src,alt){
var url = src;
var fileName = alt;
var xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.responseType = "blob";
xhr.onload = function(){
var urlCreator = window.URL || window.webkitURL;
var imageUrl = urlCreator.createObjectURL(this.response);
var tag = document.createElement('a');
tag.href = imageUrl;
tag.download = fileName;
document.body.appendChild(tag);
tag.click();
document.body.removeChild(tag);
}
xhr.send();
}
Upvotes: 1