如何从移动网络下载文件?

问题描述 投票:1回答:1

我能够下载文件。该代码适用于PC Web浏览器,但不适用于移动Web浏览器。如果你知道它在移动设备上是如何工作的,我将不胜感激。

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,
            })
        );
}
web mobile download
1个回答
1
投票

尝试一次!!有用。

•例如:如果要通过“下载”链接单击下载图像或文件。

(通过onClick阻止jquery)

HTML代码:输入代码所在的位置。

<a><img src="XYZ" /></a>
<p>file name</p>
<a href="XYZ" @click.prevent="_downloadImg('{{downLoad}}','file name')">Download</a>

Jquery代码:

_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();
}
© www.soinside.com 2019 - 2024. All rights reserved.