文档

文件管理最佳实践

更新时间:

mpserverless.file对象提供uploadFile deleteFile方法管理文件。上传的文件将通过CDN进行网络加速。

文件格式

文件存储服务目前支持上传图片、音频和视频文件。文件格式要求如下表所示。

文件类型

文件格式

图片

jpg/jpeg、png、gif、bmp、wbmp、webp、svg

音频

mp3

视频

mp4、ogg、webm

上传文件

以下代码展示了如何通过uploadFile方法以指定路径的方式上传一张公开的图片。

const options = {
  // env: public, // 不指定存储方式 env 的情况下,默认为公开(public)
  filePath: path,
  headers: {
    contentDisposition: 'attachment',
  },
};
mpserverless.file.uploadFile(options);

删除文件

以下代码展示了如何通过deleteFile方法根据文件的URL删除一个文件。

const options = {
  filePath: path,
  headers: {
    contentDisposition: 'attachment',
  },
};
mpserverless.file.uploadFile(options).then((image) => {
  mpserverless.file.deleteFile(image.fileUrl);
});

示例教程

以一个图片管理小程序为例,当用户新增一个图片条目的时候,需要上传一个图片作为附件。那么您需要让用户在添加图片时,在客户端选择一个图片上传到Serverless文件存储服务,并将得到的图片路径记录在数据存储中。

首先,增加attach()方法,作为上传图片的事件处理,用于上传图片和获取图片路径。

// client/add-image/add-image.js
// 选择并上传图片,获得图片 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);
    },
  });
},

然后,提交新增图片条目时,将图片URL作为数据一并存储到数据存储中。

// client/add-image/add-image.js
// 将新的图片内容添加到当前用户的图片列表中
add() {
  // 如果图片名称没有填,或者没有上传图片,则进行提示
  if (this.data.inputValue == '' || !this.data.imageUrl) {
    my.alert({
      title: '添加失败',
      content: '请填写图片名称和上传图片。',
      buttonText: '我知道了',
    });
  // 正常情况,写入数据存储
  } 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);
  }
},
  • 本页导读 (0)
文档反馈