在Vue3+TS+Vite+Uni+Vant4项目中使用腾讯云对象COS实现图片上传的功能 最开始时是使用import导入“cos-js-sdk-v5”依赖,但是在HBuilder打包进行真机调试时,却被提醒:
<template>
<div>
<van-form @submit="onSubmit">
<van-cell-group inset>
<van-uploader
name="avatar"
:after-read="afterRead"
v-model="fileList"
:max-count="1" />
</van-cell-group>
<div>
<van-button
round
block
type="primary"
native-type="submit">
提交
</van-button>
</div>
</van-form>
</div>
</template>
<script lang="ts" setup>
import { ref } from 'vue'
import COS, { type CosError, type PutObjectResult } from 'cos-js-sdk-v5';
import type { UploaderFileListItem } from 'vant';
const cos = new COS({
SecretId: 'XXXXXXXXXXXXXX',
SecretKey: 'xxxxxxxxxxxxxx'
})
const username = ref('');
const checked = ref('1');
const signature = ref('');
let avatarUrl = ref('');
const fileList = ref<UploaderFileListItem[]>();
const afterRead = (file: any) => {
console.log("fileeeeee",file,fileList)
// 进行腾讯云上传
cos.putObject({
Bucket: 'XXXXXXX',
Region: 'XXXXXXXX',
Key: file.file.name,
StorageClass: 'XXXXXX', /
Body: file.file,
onProgress: (progressData: any) => {
console.log(progressData);
}
}, (err: any, data: any) => {
// 文件上传或失败执行的函数,注意修改为箭头函数,否则函数中this的指向不是vue实例
console.log('成功返回数据', data)
console.log('errorrrr', err)
if (data.statusCode === 200) {
const url = `https://${data.Location}`// 把获取到的路径进行模版字符串拼接
console.log('objjjj', fileList.value);
}
})
}
</script>
所以按照提示,又将
import COS, { type CosError, type PutObjectResult } from 'cos-js-sdk-v5';换成了import COS from 'cos-nodejs-sdk-v5';
但是此时在项目编译启动时就又会报错:
最后,我按照尝试按照腾讯云官网的写法使用require来引入cos-nodejs-sdk-v5:
const COS=require(cos-nodejs-sdk-v5)然后又基于Vite不支持require导包,又去网上找了几个相关插件来进行自动编译,但是HBuilder在编译运行的时候还是又会报错:
半个月时间一直困在这个问题上面,迟迟找不到解决方法,还是太菜了