uniapp upload pictures and videos

1. uni.uploadFile(OBJECT)

Upload local resources to the developer server, and the client initiates a  POST request, where  content-type is  multipart/form-data.  For example , after the page obtains the temporary file path of a local resource
through  an interface such as uni.chooseImage , it can upload the local resource to the designated server through this interface. In addition, for selecting and uploading non-image and video files, please refer to: uni-app Selecting and uploading non-image and video files - DCloud Q&A .

When each mini program platform is running, network-related APIs need to be configured with a domain name whitelist before use.

It is recommended that developers use better APIs uniCloud.uploadFile. uniCloud provides free CDN and better ease of use, including secure cdn direct transfer. For details, see: Overview | uni-app official website

OBJECT parameter description

parameter name type Required illustrate Platform differences explained
url String yes Developer server url
files Array no List of files to be uploaded. When using files, filePath and name have no effect. App、H5( 2.6.15+)
fileType String See platform differences description File type, image/video/audio Only Alipay applet and required.
file File no The file object to upload. Only supported by H5 (2.6.15+)
filePath String yes The path of the file resource to be uploaded.
name String yes The key corresponding to the file. Developers can obtain the binary content of the file through this key on the server side.
header Object no HTTP request header, Referer cannot be set in the header.
timeout Number no Timeout time, unit ms H5(HBuilderX 2.9.9+)、APP(HBuilderX 2.9.9+)
formData Object no Other additional form data in HTTP requests
success Function no Callback function for successful interface call
fail Function no Callback function for interface call failure
complete Function no The callback function at the end of the interface call (executed whether the call is successful or failed)

Note :

  • The App supports multiple file uploads, while the WeChat applet only supports single file uploads. To upload multiple files, you need to call this API repeatedly. Therefore, the cross-end writing method is to call this API in a loop.
  • Customer service feedback in hello uni-app supports multiple image uploads. There are also multiple packaged components in the uni-app plug-in market .
  • App platform selects and uploads non-image and video files, refer to uni-app Select and upload non-image and video files - DCloud Q&A
  • Network requests  超时时间 can  manifest.json be configured  uniformly in networkTimeout .
  • The http status code returned by the Alipay mini program development tool for uploading files is in the form of a string, and the status code returned by the real machine of the Alipay mini program is in the digital form.

files parameter description

The files parameter is an array of file objects. The structure of the file object is as follows:

parameter name type Required illustrate
name String no When multipart is submitted, the form's item name defaults to file.
file File no File object to be uploaded, only supported by H5 (2.6.15+)
uri String yes local address of file

Tip:

  • If  name it is not filled in or the values ​​filled in are the same, the server may only be able to read one file when reading the file.

success return parameter description

parameter type illustrate
data String Data returned by the developer server
statusCode Number HTTP status code returned by the developer server

Example

uni.chooseImage({
    success: (chooseImageRes) => {
        const tempFilePaths = chooseImageRes.tempFilePaths;
        uni.uploadFile({
            url: 'https://www.example.com/upload', //仅为示例,非真实的接口地址
            filePath: tempFilePaths[0],
            name: 'file',
            formData: {
                'user': 'test'
            },
            success: (uploadFileRes) => {
                console.log(uploadFileRes.data);
            }
        });
    }
});

return value

If you want to return an  uploadTask object, you need to pass in at least one of the success / fail / complete parameters. For example:

var uploadTask = uni.uploadFile({
    url: 'https://www.example.com/upload', //仅为示例,并非真实接口地址。
    complete: ()=> {}
});
uploadTask.abort();

If no success/fail/complete parameters are passed in, the encapsulated Promise object will be returned: Promise encapsulation

Pass  uploadTask, you can monitor upload progress change events and cancel the upload task.

List of methods for the uploadTask object

method parameter illustrate
abort Interrupt upload task
onProgressUpdate callback Monitor upload progress changes
onHeadersReceived callback Listen for HTTP Response Header events. Will be earlier than the request completion event, only 微信小程序平台supported, specification details
offProgressUpdate callback Cancel monitoring of upload progress change events, only 微信小程序平台supported, specification details
offHeadersReceived callback Cancel listening to HTTP Response Header events, only 微信小程序平台supported, specification details

onProgressUpdate return parameter description

parameter type illustrate
progress Number Upload progress percentage
totalBytesSent Number The length of the uploaded data, unit: Bytes
totalBytesExpectedToSend Number The total length of data expected to be uploaded, in Bytes

Example

uni.chooseImage({
    success: (chooseImageRes) => {
        const tempFilePaths = chooseImageRes.tempFilePaths;
        const uploadTask = uni.uploadFile({
            url: 'https://www.example.com/upload', //仅为示例,非真实的接口地址
            filePath: tempFilePaths[0],
            name: 'file',
            formData: {
                'user': 'test'
            },
            success: (uploadFileRes) => {
                console.log(uploadFileRes.data);
            }
        });

        uploadTask.onProgressUpdate((res) => {
            console.log('上传进度' + res.progress);
            console.log('已经上传的数据长度' + res.totalBytesSent);
            console.log('预期需要上传的数据总长度' + res.totalBytesExpectedToSend);

            // 测试条件,取消上传任务。
            if (res.progress > 50) {
                uploadTask.abort();
            }
        });
    }
});

Guess you like

Origin blog.csdn.net/m0_67388537/article/details/131804335