uni.downloadFile Android端下载文件后缀带.bin解决方案

556 阅读1分钟

原因

uni.downloadFile下载是发起的一个GET请求,一般来说上传和下载为同域名,上传以二进制文件流形式上传,所以当访问这个地址以GET请求进行下载时也会以二进制文件进行下载,就会导致下载文件后缀带.bin。此时也没有办法在服务端Content-Type,改了之后会导致没有办法上传文件。

解决方案

使用plus.downloader.createDownload进行下载,修改filename属性 自己只测试了Android端,iOS和小程序没有尝试,感兴趣的朋友可以自己尝试一下

downdPdf(item) {
    // 我的item为Object
    /**
     * item = {
     *     FileName: "xxx.pdf",
     *     Url: "http://***************"
     }
    */
    var dtask =  plus.downloader.createDownload(
        item.Url,{
            filename: '_downloads/' + item.FileName
        },
        (d, status) => {
            if (status == 200) {
                // 下载成功弹出模态框提醒打开文件
                uni.showModal({
                    title: '提示',
                    content: '文件已保存:' + '_downloads/' + item.FileName,
                    cancelText: '我知道了',
                    confirmText: '打开文件',
                    success: function(res) {
                        if (res.confirm) {
                            // 打开文件
                            uni.openDocument({
                                filePath: '_downloads/' + item.FileName,
                                fileType: 'pdf',
                                success: sus => {
                                    console.log('成功打开')
                                }
                            })
                        }
                    })
                })
            } else {
                // 下载失败
                console.log('Download failed: ' + status);
            }
        })
        dtask.start();
    )
}