uni-app使用七牛上传

2021-06-24 18:16:36

记录如何在uni-app中使用七牛上传

最近公司的一个uni-app项目需要使用七牛上传,这里简单记录一下做法

  1. 获取七牛上传token

  2. 生成文件上传用的uuid


function GlobalGetUuid() {
    let d = new Date().getTime()
    const uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(
        c
    ) {
        const r = (d + Math.random() * 16) % 16 | 0
        d = Math.floor(d / 16)
        return (c == 'x' ? r : (r & 0x7) | 0x8).toString(16)
    })
    return uuid
}
  1. 选择图片上传

uni.chooseImage({
    count: 9,
    success: async (res) => {
        for (let i = 0, len = res.tempFiles.length; i < len; i++) {
            res.tempFiles[i].fileType = res.tempFiles[i].name.substr(res.tempFiles[i].name
                .lastIndexOf(".") + 1);
            res.tempFiles[i].fileKey = GlobalGetUuid() + '.' + res.tempFiles[i].fileType;
            await uni.uploadFile({
				url: 'https://up-z0.qiniup.com',
				filePath: res.tempFiles[i]['path'],
				name: 'file',
				formData: {
					'key': res.tempFiles[i]['fileKey'],
					'token': '上传token'
				},
				async success(res) {
					let data = JSON.parse(res.data);
					console.log(data)
					...
				},
				async fail(err) {
					...
				}
			});
        }
    }
})

上传操作还是比较简单的,主要利用官方的 uni.uploadFile 方法,上传地址为七牛的上传域名,formData 传入文件的 key 以及token

参考资料

本文链接:
版权声明:本博客所有文章除特别声明外,均采用 CC BY-NC-ND 3.0 许可协议。可自由转载、引用,但需署名作者且注明文章出处。如转载至微信公众号,请在文末添加作者公众号二维码。

扫描下方二维码阅读当前文章

浏览器、微信扫码

评 论:

好文推荐
每天进步一点点~