本文介绍如何使用阿里云小程序云Serverless服务端SDK上传文件到文件存储。

向文件存储中上传文件分为三步。

  1. 获取上传文件签名。
  2. 使用第一步得到的签名,直传文件到OSS。
  3. 标记文件已上传完成。

以下为NodeJS调用服务端SDK上传文件示例代码:

const Core = require('@alicloud/pop-core');
const runscript = require('runscript');

const client = new Core({
  accessKeyId: 'uFBT0jSx2S5AtLHy',
  accessKeySecret: 'xxxxxxxxxxxxxxxxxxxxxx',
  endpoint: 'https://mpserverless.aliyuncs.com',
  apiVersion: '2019-06-15'
});

const ContentType = 'text/html';
const filePath = 'index.html';
const SpaceId = '81dd5357-7d48-4616-8cbf-b4308dd*****';

const params1 = {
  "RegionId": "cn-hangzhou",
  "Filename": filePath,
  "Size": 240, //size可以随意填写,无影响
  SpaceId,
  ContentType,
};

const params2 = {
  "RegionId": "cn-hangzhou",
  SpaceId,
};

const requestOption = {
  method: 'POST'
};

async function main() {
  const result1 = await client.request('DescribeFileUploadSignedUrl', params1, requestOption);
  const {Id, SignUrl} = result1;
  console.log(Id);
  console.log(SignUrl);
  console.log(result1);

  const script = `curl -X PUT -H 'Content-Type:${ContentType}' -T 'index.html' '${SignUrl}'`;
  console.log(script);
  const scriptResult = await runscript(script);
  console.log(scriptResult);

  params2.Id = Id;
  const result2 = await client.request('RegisterFile', params2, requestOption);
  console.log(result2);
};

main().then();