Preview and download of uniapp pictures or files, compatible with ios+Android+browser+WeChat H5

I. Introduction

In the daily development of uniapp's APP, we often encounter some compatibility problems, such as the preview and download of pictures mentioned in this article. In the development of this function, I often encounter the following four problems:

  • The picture preview function is realized, but PDF, word, xls files cannot be opened.
  • The picture preview and file viewing functions of Android are normal, but the mobile phones of the ios system have frequent problems, and the files cannot be opened from time to time.
  • The picture can be opened for the first time, but a 404 is reported for the second time, the file cannot be found.
  • The preview must not only satisfy the Android and ios systems, but also enable the browser + enterprise WeChat H5 to be able to open the file preview.

2. The picture preview function is realized, but PDF, word, xls files cannot be opened

uni.previewImage()It is the picture preview API of uniapp, which is often uni.chooseImage()used together with uniapp, but we only use it in this article uni.previewImage(). Note: This API only supports opening image type files.

According to the official website document, there is only one required parameter, that is urls, the path of the picture, because this parameter is an array, when I use it, I put the path directly into an array and use it, currentthis parameter is the index value of the url, If not written, the default is 0.

       	// 预览图片
        let url = 'https://www.123.com/'
		uni.previewImage({
    
    
            current: 0,
			urls: [url],
			success: function(data) {
    
    
					console.log('预览成功');
				},
			fail: function(err) {
    
    
					console.log(‘预览失败++err.errMsg);
				}	
		});

3. The picture preview and file viewing functions of Android are normal, but the mobile phone of ios system has frequent problems, and files cannot be opened from time to time.

uni.downloadFile(): Download the file to the local, and return the temporary path after the file is downloaded. Required parameter url, string type.
uni.saveFile(OBJECT): Save the file locally.
uni.openDocument(): Open the file in a new page, support doc, xls, ppt, pdf, docx, xlsx, pptx formats, often used in conjunction with file download.

The simple usage is as follows:

uni.downloadFile({
    
    
    url: url,
    success: function(res) {
    
    
             var filePath = res.tempFilePath;
             uni.saveFile({
    
    
                 tempFilePath:filePath,
                 success:function(res){
    
    
                     //保存成功并打开文件
                     uni.openDocument({
    
    
                        filePath: filePath,
                        success: (res) => console.log('成功打开文档'),
                        fail:(res)=>{
    
    
						uni.showToast({
    
    
                            icon:'none',
                            title:'文件打开失败',
                            duration:2000
                        })
                       }
                    })
                 }
             })
        }
});

This function is in the initial version, because I found that this method can also open jpg, png and other image formats. With a fluke mentality, I will use this set of codes to download and preview regardless of the type. Later, Android The image preview and file viewing functions are normal, but the ios mobile phone has frequent problems, and the files cannot be opened from time to time. Several versions have been changed, but the problem has not been fundamentally solved.

Later, I found out that every time I open a picture, the Android phone opens it directly to the photo album, but the iOS one opens it directly on the basis of the app page. I suspect that the download cache mechanism of the iOS system is different from that of Android, and this problem occurs. Later, I thought of a more complete method (shown in Chapter 6).

4. The picture can be opened for the first time, but 404 is reported for the second time, the file cannot be found

This problem seems to be due to our backend. According to the requirements of the backend, every time I visit the picture link, I will add a timestamp to the back to ensure that the end of the link is different every time. It can be solved.

5. The preview should not only satisfy Android and ios systems, but also enable browsers to open file previews

The browser window.open(url,'_blank')can be opened immediately after use. _blankIt is stipulated to open the file on the newly opened page, and _selfto open the file on the current page.
Note: This method can be opened in the browser, but it may not be effective when it is published to H5. I originally thought that the opening of H5 is similar to the opening method of a browser, so seeing that the browser can be opened, there is no test. Recently, I suddenly discovered that this method can only be used in browsers. If you want to open the enterprise WeChat H5 terminal, you need to use itwindow.location.assign(url); .

Sixth, the final version - compatible with Android, ios, browser

The following is the final result of my repeated defeats and practice. It not only meets the compatibility issues of Android, ios, and browsers, but also meets the conditions that both pictures and files can be previewed.

Knowledge supplement: By using #ifdef, #endif, #ifdef indicators, we can separate some specific codes.

let url = data.url
let type = data.type

//如果是app走这里
//#ifdef APP-PLUS
let times = Date.parse(new Date());//拼接时间戳(根据自己项目需要考虑是否拼接)
uni.downloadFile({
    
    
    url: url+'?code='+times,
    success: function(res) {
    
    
    var filePath = res.tempFilePath;
    if (type=== 'jpg' || type === 'jpeg' || type === 'png' || type === 'gif' ) {
    
    
        //如果是图片走这里
		uni.previewImage({
    
    
            current: 0,
            urls: [url],
	})
    }else{
    
    
        //如果是文件走这里
		uni.openDocument({
    
    
            filePath: filePath,
            success: (res) => console.log('成功打开文档'),
            fail:(res)=>{
    
    
                uni.showToast({
    
    
                    icon:'none',
                    title:'文件打开失败',
                    duration:2000
                    })
            }
        })
    }
}
});
//#endif
//#ifdef H5
//如果是浏览器走这里
window.open(url,'_blank');
//如果是H5走这里,如果这里没效果,可以把window.open(url,'_blank');注释掉试试
window.location.assign(url);
//#endif

Creation is not easy, can you give me a thumbs up~

Guess you like

Origin blog.csdn.net/qq_45091359/article/details/127727201