English
Developers use the cloud storage of uniCloud
, and no longer need to separately purchase storage space, CDN mapping, traffic procurement, etc. as in the traditional model;
There are 3 ways to upload to cloud storage:
uniCloud.uploadFile
in front-end js, or use uni ui's FilePicker component, file Select + upload are all packaged.uniCloud.uploadFile
in cloud function jsNotice:
uniCloud.uploadFile
. Please don't confuse.uni.uploadFile
的API,那个API用于连接非uniCloud的上传使用。请不要混淆。The requested URL '/1123.jpg' was not found on this server
这种错误,一般是cdn流量用尽导致的,可以升级套餐或转为按量计费。阿里云的云存储有一些限制:
Tencent Cloud does not have the above restrictions.
uniCloud Tencent Cloud Edition supports file permissions for cloud storage. When the uploaded files do not want to be accessed by others, you need to configure permissions. such as ID photos.
First of all, in the uniCloud web console, in the service space of Tencent Cloud, you can configure the permissions of cloud storage. If it is a private file, it should be configured so that only administrators can access it.
In the cloud function, get the temporary URL of the file through uniCloud.getTempFileURL
(see below). Then the temporary URL is sent to the client, and the client requests the file stored in the cloud according to the temporary URL.
支付宝小程序云和腾讯云支持以上传时指定的cloudPath作为文件路径进行文件存储。
阿里云在HBuilderX 3.8.5
及之后版本支持以上传时指定的cloudPath作为文件路径进行文件存储,需要在上传时指定参数cloudPathAsRealPath: true
来启用目录支持。为兼容旧版阿里云表现cloudPathAsRealPath
默认为false
。对于客户端和本地云函数此调整在HBuilderX 3.8.5
及之后的版本生效,对于云端云函数此调整自2023年6月17日生效。
阿里云在cloudPathAsRealPath
为false
时传的文件都存储在cloudstorage
目录下,2023年6月17日起访问uniCloud web控制台云存储页面可以看到目录结构。需要注意cloudPathAsRealPath
为true
时,云函数使用同样的cloudPath上传文件会覆盖旧文件,客户端使用同样的cloudPath则会报policy_does_not_allow_file_overwrite
。
阿里云文件列表在控制台支持两种模式:
名称正序排序
。更新时间倒序排序
。开发者可结合两种模式来上传及查看文件。
Perform cloud storage operations on the front end of uni-app (not in cloud functions), including uploading and deleting files on the front end.
Tencent Cloud supports configuring cloud storage permissions, which needs to be used with Tencent Cloud custom login. Details: custom login
支付宝小程序云与阿里云不支持控制前端访问云储存的权限
The cloud storage client API will use uni.request
and uni.uploadFile
to send requests internally. If there are these two interfaces, write interceptors to accurately distinguish the content to be intercepted
Upload files directly to cloud storage.
The client uploads the file to the cloud function, and the cloud function uploads the file to the cloud storage. This process will result in a large bandwidth consumption of file traffic. Therefore, the uploaded files are generally uploaded directly from the client.
支付宝小程序云、阿里云、腾讯云的单文件大小限制为5GB
Alipay applet development tool may return a failure when uploading files to Tencent Cloud, please refer to the real machine
When each Mini Program platform is running, network-related APIs need to be configured with a whitelist of domain names before using them. Reference
已知问题
Object object
参数名 | 类型 | 必填 | 默认值 | 说明 | 平台差异说明 |
---|---|---|---|---|---|
filePath | String | 是 | - | 要上传的文件对象 | - |
cloudPath | String | 是 | - | 使用支付宝小程序云或腾讯云时,表示文件的绝对路径,包含文件名。 使用阿里云时, cloudPath 为云端文件名,传cloudPathAsRealPath: true 可以让cloudPath作为文件存储路径 | - |
cloudPathAsRealPath | Boolean | 否 | false | 是否以cloudPath 作为云端文件绝对路径 | 仅阿里云支持 |
fileType | String | - | - | 文件类型,支付宝小程序、钉钉小程序必填,可选image、video、audio | - |
onUploadProgress | Function | 否 | - | 上传进度回调 | - |
Notice
cloudPath
为云端文件名,请勿使用非法字符cloudPath
为文件的绝对路径,包含文件名 foo/bar.jpg、foo/bar/baz.jpg 等,不能包含除[0-9 , a-z , A-Z]、/、!、-、_、.、、*和中文以外的字符,使用 / 字符来实现类似传统文件系统的层级结构。cloudPath
为文件标识,相同的cloudPath
会覆盖,如果没有权限覆盖则会上传失败。阿里云以自动生成的ID为文件标识,不会存在覆盖问题About whether Tencent Cloud has permission to overwrite/delete cloud files
Tencent Cloud uses custom login to determine user identity. The following uses the default permission "readable by all users, writable only by creators and administrators" as an example to explain
By default users log in as anonymous (for convenience we will temporarily call this identity "Anonymous User A")
After the identity of anonymous user A expires, the identity obtained again is not "anonymous user A" (which is temporarily referred to as "anonymous user B"). At this time, anonymous user B does not have permission to overwrite the files uploaded by anonymous user A.
If custom login is used, then cloud storage can determine the user's identity. At this time, the user can overwrite the files uploaded by himself, and delete them in the same way.
Field | Type | Description |
---|---|---|
fileID | String | The unique ID of the file, used to access the file, it is recommended to store it |
requestId | String | Request serial number, used for troubleshooting |
// front end code
uni.chooseImage({
count: 1,
success(res) {
console.log(res);
if (res.tempFilePaths.length > 0) {
let filePath = res.tempFilePaths[0]
//Perform upload operation
// promise method
const result = await uniCloud.uploadFile({
filePath: filePath,
cloudPath: 'a.jpg',
onUploadProgress: function(progressEvent) {
console.log(progressEvent);
var percentCompleted = Math.round(
(progressEvent.loaded * 100) / progressEvent.total
);
}
});
// callback method, you can choose one of the two methods with the promise method
uniCloud.uploadFile({
filePath: filePath,
cloudPath: 'a.jpg',
onUploadProgress: function(progressEvent) {
console.log(progressEvent);
var percentCompleted = Math.round(
(progressEvent.loaded * 100) / progressEvent.total
);
},
success() {},
fail() {},
complete() {}
});
}
}
});
Tips
在客户端把文件的fileid转换为临时URL。临时URL有有效期限制,避免其他人获取URL后可以持续访问该文件。
Platform Compatibility
阿里云 | 腾讯云 | 支付宝小程序云 |
---|---|---|
√ | √ | √ |
支付宝小程序云与腾讯云获取文件临时下载链接。
Since HBuilderX 3.1.0, Alibaba Cloud also supports this interface, but only to smooth out the interface differences with Tencent Cloud. Because Alibaba Cloud's cloud storage does not support permission control.
Field | Type | Required | Default | Description | Platform Difference Description |
---|---|---|---|---|---|
fileList | Array<String> | Yes | - | Array of file IDs to get download links | - |
fileList in request parameters
Fields | Type | Required | Description |
---|---|---|---|
fileID | String | Yes | FileID |
Field | Type | Description |
---|---|---|
fileList | Array<Object> | Array storing download links |
requestId | String | Request serial number, used for troubleshooting |
fileList in response parameters
Field | Type | Description |
---|---|---|
fileID | String | File ID |
tempFileURL | String | File access link |
// The client gets the sample source code of the temporary file
// promise method
uniCloud.getTempFileURL({
fileList: ['cloud://test-28farb/a.png']
})
.then(res => {});
//callback method, choose one from promise method
uniCloud.getTempFileURL({
fileList: ['cloud://test-28farb/a.png'],
success() {},
fail() {},
complete() {}
});
After Alibaba Cloud migrates the service space, the old cloud storage url needs to obtain the CDN link of the new service space through this interface
Platform Compatibility
阿里云 | 腾讯云 | 支付宝小程序云 |
---|---|---|
HBuilderX 3.6.10+(Alpha版)、HBuilderX 3.6.5+(正式版) | 不支持 | 不支持 |
Field | Type | Required | Default Value | Description | Platform Difference Description |
---|---|---|---|---|---|
fileList | Array<String> | Yes | - | Array of file IDs to get download links | - |
fileList in the request parameter
Field | Type | Required | Description |
---|---|---|---|
fileID | String | yes | old cloud storage url |
Field | Type | Description |
---|---|---|
fileList | Array<Object> | Array storing download links |
fileList in the response parameter
Field | Type | Description |
---|---|---|
fileId | string | file ID (id parsed from the file url) |
gmtCreate | number | File upload time (time stamp accurate to seconds) |
gmtModified | number | File modification time (time stamp accurate to the second) |
name | string | Original file name |
size | number | file size (Byte) |
type | string | file type |
url | string | file cdn link |
Supported since HBuilderX 3.1.0
Select files (pictures/videos) via ui interface and upload directly to cloud storage.
At the same time, a selection callback event is provided, which is convenient for secondary processing such as compression of the selected image before uploading.
The receiving compatibility of this interface is slightly different depending on the type
Select image, type:'image'
App | H5 | 微信小程序 | 支付宝小程序 | 百度小程序 | 抖音小程序、飞书小程序 | QQ小程序 | 快手小程序 | 京东小程序 |
---|---|---|---|---|---|---|---|---|
√ | √ | √ | √ | √ | √ | √ | √ | √ |
Select video, type:'video'
App | H5 | 微信小程序 | 支付宝小程序 | 百度小程序 | 抖音小程序、飞书小程序 | QQ小程序 | 快手小程序 | 京东小程序 |
---|---|---|---|---|---|---|---|---|
√ | √ | √ | √ | √ | √ | √ | √ | √ |
Select any file, type:'all'
App | H5 | 微信小程序 | 支付宝小程序 | 百度小程序 | 抖音小程序、飞书小程序 | QQ小程序 | 快手小程序 | 京东小程序 |
---|---|---|---|---|---|---|---|---|
× | √ | √ (Only supports selecting chat files) | × | × | × | × | × | × |
This interface receives different parameters according to the type
Select image, type:'image'
Fields | Type | Required | Description |
---|---|---|---|
type | String | Yes | File type, image (picture), video (video), all (any file) |
count | Number | No | Number of files, default 9 |
extension | Array | No | File Suffix |
sizeType | Array | No | original original image, compressed compressed image, both by default, valid when type is image |
sourceType | Array | No | album Select image from album, camera uses camera, both are available by default |
Select video, type:'video'
Fields | Type | Required | Description |
---|---|---|---|
type | String | Yes | File type, image (picture), video (video), all (any file) |
extension | Array | No | File Suffix |
camera | String | No | Camera switch, front (front camera), back (rear camera) |
compressed | Boolean | No | Whether to compress the selected video source file, the default value is true, compression is required, type |
sourceType | Array | No | album Select image from album, camera uses camera, both are available by default |
Select file, type:all
Fields | Type | Required | Description |
---|---|---|---|
type | String | Yes | File type, image (picture), video (video), all (any file) |
count | Number | No | Number of files |
extension | Array | No | File Suffix |
illustrate
onChooseFile(Object OnChooseFileRes)
The callback event for the selected image. It is convenient to perform secondary processing such as compression and cropping on the selected image, and then upload it.
The structure of OnChooseFileRes is as follows
{
errMsg: '',
tempFilePaths: [], // 临时文件路径数组,chooseVideo/chooseImage/chooseFile接口返回的tempFilePath组成的数组
tempFiles: [] // 临时文件组成的数组
}
If the onChooseFile callback has a return value, this return value will be used to replace the actual selected file for uploading. Additional processing of the file can be done within this callback, blocking the upload by returning a promise within onChooseFile, during which additional processing of the file can be done.
example:
function cropImg(file) {
return new Promise((resolve, reject) => {
let ext
let filePathProcessed = file.path // 处理结果
// #ifdef H5
ext = file.name.split('.').pop()
resolve({
path: filePathProcessed,
ext,
fileType: file.fileType
})
// #endif
// #ifndef H5
uni.getImageInfo({
src: file.path,
success(info) {
ext = info.type.toLowerCase()
resolve({
path: filePathProcessed,
ext,
fileType: file.fileType
})
},
fail(err) {
reject(new Error(err.errMsg || '未能获取图片类型'))
}
})
// #endif
})
}
uniCloud.chooseAndUploadFile({
type: 'image',
onChooseFile(res) {
const processAll = []
for (let i = 0; i < res.tempFiles.length; i++) {
processAll.push(cropImg(res.tempFiles[i]))
}
return Promise.all(processAll).then((fileList) => {
let result = {
tempFilePaths: []
}
result.tempFiles = fileList.map((fileItem, index) => {
result.tempFilePaths.push(fileItem.path)
return {
path: fileItem.path,
cloudPath: '' + Date.now() + index + '.' + fileItem.ext, // 云端路径,这里随便生成了一个
fileType: fileItem.fileType
}
})
return result
})
}
}).then(res => {
console.log(res)
})
OnUploadProgress(Object OnUploadProgressRes)
Upload progress callback
The structure of OnUploadProgressRes is as follows
{
index: 0, // 触发此回调的文件序号
loaded: 256, // 已上传大小
total: 1024, // 总大小
tempFilePath: '', // 本地临时文件路径
tempFile: {} // 本地文件对象
}
The response parameters in the success callback are in the following form
{
errMsg: '', // 错误信息
tempFilePaths: [], // 本地临时文件路径组成的数组
tempFiles: [] // 文件对象数组,每项上都被追加了一个url属性,值为文件上传得到的fileID
}
// promise method
uniCloud.chooseAndUploadFile({
type: 'image'
})
.then(res => {});
//callback method, choose one from promise method
uniCloud.chooseAndUploadFile({
type: 'image',
success(res) {},
fail() {},
complete() {}
});
The client deletes cloud storage files.
This API is deprecated. Deleting cloud storage files is a high-risk operation, and cloud functions should delete cloud storage files after permission verification.
Object object
Fields | Type | Required | Description |
---|---|---|---|
fileList | <Array>.String | 是 | 要删除的文件 ID 组成的数组 |
Fields | Type | Required | Description |
---|---|---|---|
fileList | <Array>.Object | No | Array of delete results |
requestId | String | No | Request serial number for troubleshooting |
fileList definition
Fields | Type | Required | Description |
---|---|---|---|
fileID | String | Yes | FileID |
// promise
uniCloud
.deleteFile({
fileList: ['cloud://jimmytest-088bef/1534576354877.jpg']
})
.then(res => {});
// callback
uniCloud.deleteFile(
{
fileList: ['cloud://jimmytest-088bef/1534576354877.jpg'],
success(){},
fail(){},
complete(){}
}
);
In some scenarios, it is necessary to use the cloud storage of the service space not associated with the client. At this time, uniCloud.init method to obtain an instance of the corresponding space for uploading files
Example Code
const storageSpace = uniCloud.init({
provider: 'aliyun',
spaceId: 'mp-xxxx',
clientSecret: 'xxxx',
endpoint: 'https://api.next.bspapp.com'
})
const uploadRes = await storageSpace.uploadFile({
filePath: '',
cloudPath: ''
})
Operate cloud storage files in cloud functions (not in the front end), including uploading and deleting cloud storage files in cloud functions.
Cloud function upload files to cloud storage.
If the file is uploaded from the client, it is generally not recommended to upload the file from the client to the cloud function first, and then upload the file to the cloud storage from the cloud function. Instead, it is recommended that the client directly upload the cloud storage. See: https://uniapp.dcloud.io/uniCloud/storage?id=uploadfile
Platform Compatibility
阿里云 | 腾讯云 | 支付宝小程序云 |
---|---|---|
√ | √ | √ |
If HBuilderX versions before 3.1.0 use Alibaba Cloud, please upload through uniCloud.uploadFile
on the client side
uploadFileOptions parameter description
字段 | 类型 | 必填 | 默认值 | 说明 | 平台差异说明 |
---|---|---|---|---|---|
cloudPath | string | 是 | - | 使用腾讯云或支付宝小程序云时,表示文件的绝对路径,包含文件名。 使用阿里云时, cloudPath 为云端文件名,传cloudPathAsRealPath: true 可以让cloudPath作为文件存储路径 | |
fileContent | - | 是 | - | 文件内容,请看下方说明 | |
cloudPathAsRealPath | Boolean | 否 | false | 是否以cloudPath 作为云端文件绝对路径 | 仅阿里云支持 |
illustrate
Fields | Type | Required | Description |
---|---|---|---|
fileID | fileID | Yes | The unique ID of the file, used to access the file, it is recommended to store it. |
requestId | string | No | Request serial number, used for error troubleshooting. |
// Cloud function upload file sample code
const fs = require("fs");
let result = await uniCloud.uploadFile({
cloudPath: "test-admin.jpeg",
fileContent: fs.createReadStream(`${__dirname}/cos.jpeg`)
});
Cloud Function Get the file download link.
Platform Compatibility
阿里云 | 腾讯云 | 支付宝小程序云 |
---|---|---|
× | √ | √ |
getTempFileURLOptions parameter description
Fields | Type | Required | Description |
---|---|---|---|
fileList | <Array>.string | Yes | an array of file IDs to download. |
fileList field
Fields | Type | Required | Description | ||
---|---|---|---|---|---|
fileID | string | yes | File ID. | ||
<!-- | maxAge | Integer | yes | file link validity period. | --> |
Fields | Type | Required | Description |
---|---|---|---|
fileList | <Array>.object | no | Array to store download links. |
requestId | string | No | Request serial number, used for error troubleshooting. |
fileList field
Fields | Type | Required | Description |
---|---|---|---|
fileID | string | yes | File ID. |
tempFileURL | string | yes | File access link. |
let result = await uniCloud.getTempFileURL({
fileList: ['cloud://test-28farb/a.png']
});
Cloud Function delete cloud storage files.
Deleting cloud storage files is a high-risk operation. It is not recommended to perform operations on the client, but to perform operations in cloud functions.
deleteFileOptions parameter description
Fields | Type | Required | Description |
---|---|---|---|
fileList | <Array>.string | yes | Array of file IDs to delete. |
Fields | Type | Required | Description |
---|---|---|---|
fileList | <Array>.object | no | Array of delete results. |
requestId | string | No | Request serial number, used for error troubleshooting. |
fileList field
Fields | Type | Required | Description |
---|---|---|---|
fileID | string | yes | File ID. |
// Cloud function delete file sample code
let result = await uniCloud.deleteFile({
fileList: [
"cloud://test-28farb/a.png" // 阿里云fileID是url形式,例:https://xxx.com/xxx.png
]
});
云函数下载已上传至云存储的文件到云函数代码空间内。阿里云直接使用http请求url下载即可,无需使用downloadFile接口。
如需下载到客户端请参考:
Platform Compatibility
阿里云 | 腾讯云 | 支付宝小程序云 |
---|---|---|
× | √ | √ |
downloadFileOptions parameter description
Fields | Type | Required | Description |
---|---|---|---|
fileID | string | yes | ID of the file to download. |
tempFilePath | string | no | The location where the downloaded file is to be stored. |
Fields | Type | Required | Description |
---|---|---|---|
fileContent | Buffer | no | The content of the downloaded file. This field is not returned if tempFilePath is passed in. |
requestId | string | No | Request serial number, used for error troubleshooting. |
let result = await uniCloud.downloadFile({
fileID: "cloud://aa-99j9f/my-photo.png",
// tempFilePath: '/tmp/test/storage/my-photo.png'
});
After Alibaba Cloud migrates the service space, the old cloud storage url needs to obtain the CDN link of the new service space through this interface
Platform Compatibility
阿里云 | 腾讯云 | 支付宝小程序云 |
---|---|---|
HBuilderX 3.6.10+(Alpha版)、HBuilderX 3.6.5+(正式版) | 不支持 | 不支持 |
Field | Type | Required | Default Value | Description | Platform Difference Description |
---|---|---|---|---|---|
fileList | Array<String> | Yes | - | Array of file IDs to get download links | - |
fileList in the request parameter
Field | Type | Required | Description |
---|---|---|---|
fileID | String | yes | old cloud storage url |
Field | Type | Description |
---|---|---|
fileList | Array<Object> | Array storing download links |
fileList in the response parameter
Field | Type | Description |
---|---|---|
fileId | string | file ID (id parsed from the file url) |
gmtCreate | number | File upload time (time stamp accurate to seconds) |
gmtModified | number | File modification time (time stamp accurate to the second) |
name | string | Original file name |
size | number | file size (Byte) |
type | string | file type |
url | string | file cdn link |
Alibaba Cloud Commercial Edition can still use this function, but billing may be performed in the future
When using Alibaba Cloud as the service provider, cloud storage supports the direct use of restful api to process resources. The following table lists the supported operation types.
If your database and cloud functions use Tencent Cloud, you can also use Alibaba Cloud Cloud Storage. Detailed usage reference: Connect multiple service spaces
Function | Operation Parameters | Reference Documentation |
---|---|---|
Image zoom | resize | Click to view |
Image crop | crop | Click to view |
Image rotation | rotate | Click to view |
Image sharpening adjustment | sharpen | Click to view |
Image format conversion | format | Click to view |
Image quality adjustment | quality | Click to view |
Image watermark | watermark | Click to view |
Video frame | snapshot | Click to view |
Tips
When using Tencent Cloud as a service provider, cloud storage provides image scaling, image watermarking and other computing functions through Data Vientiane
.
Data Vientiane
is a pay-as-you-go product of Tencent Cloud. The bill for the previous month is generated at the beginning of the month, and the relevant fees are deducted from the account balance. Therefore, if you use functions such as image scaling and image watermarking in Tencent Cloud, you must first ensure that the account balance is sufficient, otherwise it may trigger the risk of account-level service suspension!
Note: The bill generated at the beginning of the month of Data Vientiane
will be automatically deducted from the balance of the uniCloud account. The relevant fees and unit prices are completely consistent with Tencent Cloud. For details, please refer to [Data Vientiane - Billing Method](https://cloud.tencent .com/document/product/460/73221).
The data processing functions supported by Tencent Cloud are as follows:
Function | Operation Parameters | Reference Documentation |
---|---|---|
Image Zoom | thumbnail | Click to view |
Image crop | cut,crop,iradius,rradius,scrop | Click to view |
Image Rotate | rotate | Click to view |
Format Conversion | format,cgif,interlace | Click to view |
Quality Transform | quality,rquality,lquality | Click to view |
Gaussian Blur | radius,sigma | Click to view |
brightness | bright | Click to view |
Contrast | contrast | Click to view |
Sharpen | sharpen | Click to view |
Grayscale | grayscale | Click to view |
Image watermark | watermark | Click to view |
Text Watermark | watermark | Click to view |
Get basic image information | imageInfo | Click to view |
Get Image EXIF | exif | Click to view |
Get the main color of the image | imageAve | Click to view |
Remove meta information | strip | Click to view |
Quick Thumbnail Template | w,h,format,q,rq,lq | Click to view |
Limit image size | size-limit | Click to view |
Pipe operator | | | Click to view |