# Overview

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:

  1. Web interface: In the https://unicloud.dcloud.net.cn/ web console, click Cloud Storage to upload files through the web interface. The management interface also provides operation interfaces such as resource browsing and deletion.
  2. Client API or component upload: write uniCloud.uploadFile in front-end js, or use uni ui's FilePicker component, file Select + upload are all packaged.
  3. Cloud function uploads files to cloud storage: that is, write uniCloud.uploadFile in cloud function js

Notice:

  • Both the front end and the cloud function end have an api with the same name: uniCloud.uploadFile. Please don't confuse.
  • 前端还有一个uni.uploadFile的API,那个API用于连接非uniCloud的上传使用。请不要混淆。
  • 在使用腾讯云时如果访问云存储文件提示The requested URL '/1123.jpg' was not found on this server这种错误,一般是cdn流量用尽导致的,可以升级套餐或转为按量计费。
  • In applications that allow users to upload pictures, violation detection is essential. For this reason, uniCloud provides a content security detection module, which can easily implement functions such as image identification. For details, please refer to: Content Security

阿里云的云存储有一些限制:

  • The file has no read permission control, anyone who knows the path can read it.

Tencent Cloud does not have the above restrictions.

# File Permissions

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日生效。

阿里云在cloudPathAsRealPathfalse时传的文件都存储在cloudstorage目录下,2023年6月17日起访问uniCloud web控制台云存储页面可以看到目录结构。需要注意cloudPathAsRealPathtrue时,云函数使用同样的cloudPath上传文件会覆盖旧文件,客户端使用同样的cloudPath则会报policy_does_not_allow_file_overwrite

阿里云文件列表在控制台支持两种模式:

  • 文件夹模式:该模式下支持新建及上传指定文件到文件夹,列表按照名称正序排序
  • 文件列表模式:该模式是阿里云未支持文件夹之前的列表模式,所有文件平铺展示,列表按照更新时间倒序排序

开发者可结合两种模式来上传及查看文件。

# Client API

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

# uploadFile(Object object)

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

已知问题

  • HBuilderX 3.98之前的版本,微信小程序端上传文件到支付宝小程序云会报错
  • 非web端、微信小程序端上传文件到支付宝小程序云会出现怪异表现或者报错,例如:百度小程序会既不触发失败也不触发成功,最终会上传一个空文件上去。此问题支付宝小程序云已在2023年11月21日修复。

# request parameters

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为文件标识,不会存在覆盖问题
  • Alibaba Cloud temporarily prohibits uploading html files in cloud storage due to security reasons
  • The upload file timeout can be configured in the project manifest.json

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")

  • If the cloud path does not exist, the upload can be successful.
  • The cloud path exists and is created by anonymous user A and can be uploaded successfully
  • If the cloud path exists and is not created by anonymous user A, the upload will fail

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.

# Response parameters

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

# Sample code

// 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为链接形式可以直接使用,支付宝小程序云与腾讯云返回的为cloud://形式,如需展示需要调用getTempFileURL获取链接
  • uniCloud.uploadFile only upload, no file selection. uni ui encapsulates the FilePicker component, from selection to upload one-stop.

# getTempFileURL(Object object)

在客户端把文件的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.

# request parameters

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

# Response parameters

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

# Sample code

// 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() {}
});

# getFileInfo(Object object)

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+(正式版) 不支持 不支持

# Request parameters

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

# Response parameters

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

# chooseAndUploadFile(Object object)

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.

# Client Platform Compatibility

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) × × × × × ×

# request parameters

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

  • There is no count parameter when selecting videos, which means that only one can be selected at a time
  • The performance of the count value on the H5 platform is based on the browser's own specifications. According to the results of the current test, only single-choice/multi-choice can be limited, and the number cannot be limited. Also, few actual mobile browsers support multiple selection.

# callback method

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: {} // 本地文件对象
}

# Response parameters

The response parameters in the success callback are in the following form

{
  errMsg: '', // 错误信息
  tempFilePaths: [], // 本地临时文件路径组成的数组
  tempFiles: [] // 文件对象数组,每项上都被追加了一个url属性,值为文件上传得到的fileID
}

# Example

// promise method
uniCloud.chooseAndUploadFile({
		type: 'image'
	})
	.then(res => {});

//callback method, choose one from promise method
uniCloud.chooseAndUploadFile({
	type: 'image',
	success(res) {},
	fail() {},
	complete() {}
});

# deleteFile(Object object)

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.

  • Alibaba Cloud does not support this API, and the front-end running this API will report a permission error
  • 腾讯云支持此API,如若使用,需搭配腾讯云提供的自定义登录和权限设置使用
  • 支付宝小程序云不支持此API

# request parameters

Object object

Fields Type Required Description
fileList <Array>.String 要删除的文件 ID 组成的数组

# Response parameters

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

# Sample code

// promise
uniCloud
  .deleteFile({
    fileList: ['cloud://jimmytest-088bef/1534576354877.jpg']
  })
  .then(res => {});

// callback
uniCloud.deleteFile(
  {
    fileList: ['cloud://jimmytest-088bef/1534576354877.jpg'],
	success(){},
	fail(){},
	complete(){}
  }
);

# Transfer pictures to other service spaces

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: ''
})

# Cloud Function API

Operate cloud storage files in cloud functions (not in the front end), including uploading and deleting cloud storage files in cloud functions.

# uniCloud.uploadFile(Object uploadFileOptions)

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

# request parameters

uploadFileOptions parameter description

字段 类型 必填 默认值 说明 平台差异说明
cloudPath string - 使用腾讯云或支付宝小程序云时,表示文件的绝对路径,包含文件名。
使用阿里云时,cloudPath为云端文件名,传cloudPathAsRealPath: true可以让cloudPath作为文件存储路径
fileContent - - 文件内容,请看下方说明
cloudPathAsRealPath Boolean false 是否以cloudPath作为云端文件绝对路径 仅阿里云支持

illustrate

  • 支付宝小程序云与腾讯云支持在fileContent内传可读流 或buffer
  • Alibaba Cloud supports uploading file absolute path or buffer in fileContent

# Response parameters

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.

# Sample code

// 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`)
});

# uniCloud.getTempFileURL(Object getTempFileURLOptions)

Cloud Function Get the file download link.

Platform Compatibility

阿里云 腾讯云 支付宝小程序云
×

# request parameters

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. -->

# Response parameters

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.

# Sample code

let result = await uniCloud.getTempFileURL({
    fileList: ['cloud://test-28farb/a.png']
});

# uniCloud.deleteFile(Object deleteFileOptions)

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.

# request parameters

deleteFileOptions parameter description

Fields Type Required Description
fileList <Array>.string yes Array of file IDs to delete.

# Response parameters

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.

# Sample code

// Cloud function delete file sample code
let result = await uniCloud.deleteFile({
    fileList: [
        "cloud://test-28farb/a.png" // 阿里云fileID是url形式,例:https://xxx.com/xxx.png
    ]
});

# uniCloud.downloadFile(Object downloadFileOptions)

云函数下载已上传至云存储的文件到云函数代码空间内。阿里云直接使用http请求url下载即可,无需使用downloadFile接口。

如需下载到客户端请参考:

Platform Compatibility

阿里云 腾讯云 支付宝小程序云
×

# request parameters

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.

# Response parameters

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.

# Sample code

let result = await uniCloud.downloadFile({
    fileID: "cloud://aa-99j9f/my-photo.png",
    // tempFilePath: '/tmp/test/storage/my-photo.png'
});

# getFileInfo(Object object)

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+(正式版) 不支持 不支持

# Request parameters

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

# Response parameters

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

# data processing

# 阿里云

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

  • Alibaba Cloud's cloud storage does not currently support sub-directories. Alibaba Cloud's front-end web hosting supports sub-directory.

# 腾讯云

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