Direct transmission of OSS in uniapp to Alibaba Cloud (h5)

OSS direct transfer to Alibaba Cloud

In the mobile uniapp project, I encountered that if OSS is used to directly transmit to the Alibaba Cloud server, after various pitfalls, I finally want to summarize something, I hope it will be useful

1. Installation dependencies

npm i ali-oss --save

2. Introduce in the upload page

const OSS = require(‘ali-oss’);

3. Instantiate OSS

When instantiating oss, either use the data returned by the background, or search for it on the Alibaba Cloud server you use. There are more checks here, so I won’t say much

let client = new OSS({
 	region: 'xxxxbeijing.aliyuncs.com/', // 上传后的域名
    accessKeyId: sign.AccessKeyId, // 后台的临时签名ID
    accessKeySecret: sign.AccessKeySecret, // 后台的临时签名密钥
    stsToken: sign.SecurityToken,
    bucket: 'xxx', // OSS仓库名
});

4. Select pictures through the API of uniapp

uni.chooseImage({
    count: 3, //默认9
    sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图,默认二者都有
    sourceType: ['album'], //从相册选择
    success: function (res) {
        console.log(res);//此处res中有所需要的信息	res.tempFiles[0];
        let curTime = new Date();
		let year = curTime.getFullYear();
   		let month = curTime.getMonth() + 1;
        let day = curTime.getDate();
		let dir = 'imgs/' + year + '/' + (month < 10 ? '0' + month : month) + '-' + (day < 10 ? '0' + day : day) + '/';
		//接下来是重点   此处client是第三步中实例化的
		client.multipartUpload(dir+'文件名称', res.tempFiles[0]).then(ress=>{
               console.log(ress);//此处就已经上传成功了
              })
    }
});

Summarize

The author has encountered a lot of pitfalls in this regard. When using the following writing methods of Alibaba Cloud documents, it will report an error Must provide String/Buffer/ReadableStream for put, and then check to process blobs, but after the conversion, the type of uploaded files encountered problems again, not pictures. format, so I uploaded directly using multipartUpload, and finally uploaded successfully. If you have any questions, you can communicate. If there is a better way, you can also communicate.

  try {
    const result = await client.put('exampledir/exampleobject.txt', data);
    console.log(result);
  } catch (e) {
    console.log(e);
  }
}
putObject();

Guess you like

Origin blog.csdn.net/moanuan/article/details/120706169