The mpserverless.file object provides the uploadFile and deleteFile methods to manage files. Files that are uploaded are accelerated by CDN.
File formats
The file storage service supports image, audio, and video files. The following table lists the supported file formats.
File type | File format |
|---|---|
Image | jpg/jpeg, png, gif, bmp, wbmp, webp, svg |
Audio | mp3 |
Video | mp4, ogg, webm |
Upload a file
The following code shows how to use the uploadFile method to upload a public image by specifying its path.
const options = {
// If env is not specified, the file is public by default.
// env: public,
filePath: path,
headers: {
contentDisposition: 'attachment',
},
};
mpserverless.file.uploadFile(options);Delete a file
The following code shows how to use the deleteFile method to delete a file based on its URL.
const options = {
filePath: path,
headers: {
contentDisposition: 'attachment',
},
};
mpserverless.file.uploadFile(options).then((image) => {
mpserverless.file.deleteFile(image.fileUrl);
});Tutorial
This tutorial uses an image management miniapp as an example. When a user adds a new image item, an image is uploaded as an attachment. The user selects an image on the client and uploads it to the Serverless file storage service. The service returns an image path, which is then recorded in data storage.
First, add the attach() method to handle image uploads. This method uploads an image and retrieves its path.
// client/add-image/add-image.js
// Select and upload an image to obtain the image URL
attach() {
my.chooseImage({
chooseImage: 1,
success: res => {
const path = res.apFilePaths[0];
const options = {
filePath: path,
headers: {
contentDisposition: 'attachment',
},
};
mpserverless.file.uploadFile(options).then((image) => {
console.log(image);
this.setData({
imageUrl: image.fileUrl,
});
}).catch(console.log);
},
});
},Then, when the new image item is submitted, the image URL is also saved to data storage.
// client/add-image/add-image.js
// Add the new image content to the current user's image list.
add() {
// Display a prompt if the image name is empty or no image is uploaded.
if (this.data.inputValue == '' || !this.data.imageUrl) {
my.alert({
title: 'Failed to add',
content: 'Enter an image name and upload an image.',
buttonText: 'OK',
});
// Otherwise, write to data storage.
} else {
mpserverless.user.getInfo().then((user) => {
mpserverless.db.collection('images').insertOne({
text: this.data.inputValue,
url: this.data.imageUrl ? this.data.imageUrl : false,
userId: user.userId,
uploadTime: new Date(),
}).then(() => {
my.navigateBack();
}).catch(console.log);
}).catch(console.log);
}
},