background
Wechat small program provides developers with a downloadFile API for downloading operations, but recently, the company encountered a failure message of file data is empty when the interface was upgraded to download files on apple phones. Finally, arrayBuffer was used to solve this problem.
downloadFile
The official downloadFile interface, which passes in the corresponding parameter, returns the path to the file if it succeeds, without the need for blob,fileReader, and so on in the browser environment.
Tip: The file type is treated according to the content-Type of the response. If it is simply application/ OCtet-stream, it is the bin suffix on the development tool and the unknow suffix on the real machine
Custom download
ResponseType is arrayBuffer, and then FileSystemManager is used to save the file in binary mode.
const imgUrl = 'http://attach.bbs.miui.com/forum/201306/23/110328s72xxse7lfis9fnd.jpg';
wx.request({
url: imgUrl,
responseType: 'arrayBuffer'.success: (res) = > {
const { data } = res;
const fs = wx.getFileSystemManager();
const filePath = wx.env.USER_DATA_PATH + '/temp.jpg';
fs.writeFile({
filePath,
data,
encoding: 'binary'.success: (a)= > {
this.setData({
imgPath: filePath, }) } }); }});Copy the code
Find a picture of the network to test, the implementation code is similar to the above. But this doesn’t take into account failed downloads, handling file suffixes, etc. So the next step is to encapsulate a more practical and common method.
Tip: Check not to verify valid domain names when testing on development tools
Encapsulating common methods
const downloadFile = function(url, data, path) {
let filePath = ' ';
wx.showLoading({
title: 'Downloading... ',
mask: true});return new Promise((resolve, reject) => {
wx.pro.request({
url,
data,
responseType: 'arraybuffer',
}).then(res => {
console.log(res);
const contentType = res.header['Content-Type']; // Content-type: application/json const isErrTips = contentType.includes()'application/json');
ifConst tips = ab2Str(res.data); // Convert arrayBuffer to a string const tips = ab2Str(res.data); reject(tips); } // Use the timestamp to generate const fileFormat = contentType.includes('application/octet-stream')?'bin' : contentType.split('application/')[1].split('; ') [0]; filePath = path || (wx.env.USER_DATA_PATH +'/' + Date.now() + '. '+ fileFormat); // Save the filereturn wx.fsPro.writeFile({
filePath: filePath,
data: res.data,
encoding: 'binary'}); }).then(() => { wx.hideLoading(); // return the saved filePath resolve(filePath); }).catch(err => { wx.hideLoading(); reject(err); }); }); };Copy the code
Calling code
const imgUrl = 'http://attach.bbs.miui.com/forum/201306/23/110328s72xxse7lfis9fnd.jpg'; downloadFile(imgUrl).then(res => { console.log(res); This. setData({imgPath: res,}); }).catch(err => { console.log(err); });Copy the code
The public method simply encapsulates the request, save the file function, and finally return the file path, basically and the official downloadFile function provided, but further processing background response error processing, the demo will bE wechat API into a Promise object, so you can chain call.
Note that the saved file is in the user directory provided by the small program, the maximum 10m, so when not in use, manually delete. DownloadFile is stored in a temporary directory, which wechat will clean up when it gets the chance. Look at the applets file system
Background the returned exception handling another train of thought is that can, like the official downloadFile, regardless of the outcome, save the results to a file, the final use FileSystemManager. ReadFile to read the file content, utf8 encoding.
- Download successful
- An error message is displayed
conclusion
This article mainly introduces how to use the ordinary Wx. request interface, to realize the function of downloading files. Can be used mainly in:
- Call the official downloadFile in some models of the unexpected situation, after all, we do not have micro channel small program bottom source, can not locate the specific problem, in the official has not been solved, you can use the “curve to save the country” solution
- The official downloadFile handles the file type based on the conten-type of the response, but all background file streams are application/octet-stream. With this method, you can set the path and file suffix in advance if you know the return type
- When downloading the file, the background returns an error message, the method in this article is more humane processing, not all results are saved as a file
The disadvantages are:
- The file should be saved in the user directory provided by wechat, which needs to be manually deleted. It cannot be saved in a temporary directory like the official downloadFile, which does not need to be manually cleaned. This deficiency is unavoidable.
Finally, the demo address is attached