使用网站
七牛云在线生成token
一般是后端生成,使用接口获取(放在后端比较安全)
// 获取七牛云token
export async function getQiniuToken() {
const url = '/upload/key';
const result = await defHttp.get({ url });
return result || '';
}
上传方法
// 用户上传图片到七牛云
export async function uploadPictureToQiniu(file: File): Promise<string> {
const qiniuConfig = {
uploadURL: 'https://up-z2.qiniup.com',
// 其他配置...
};
const uploadKey = `hq-artist/end/end_${Date.now()}${Math.floor(Math.random() * 100)}.png`; // 使用 Date.now() 生成基于时间的唯一标识
try {
// 假设 getQiniuToken 是一个返回 Promise 的函数,它获取七牛云的上传令牌
const token = await getQiniuToken();
const formData = new FormData();
formData.append('file', file);
formData.append('token', token);
formData.append('key', uploadKey);
const config = {
headers: { 'Content-Type': 'multipart/form-data' },
};
const response = await axios.post(qiniuConfig.uploadURL, formData, config);
return response.data.key || uploadKey; // 返回上传的文件key
} catch (error) {
// 处理上传过程中可能出现的错误
console.error('Upload failed:', error);
throw error; // 重新抛出错误,以便调用者可以进一步处理
}
}
使用
<a-upload
:listType="listType"
accept="image/*"
:multiple="multiple"
:auto-upload="true"
:headers="headers"
:data="{ biz: bizPath }"
v-model:fileList="uploadFileList"
:beforeUpload="beforeUpload"
:disabled="disabled"
:customRequest="uploadQiniu"
@change="handleChange"
@preview="handlePreview"
>
<div v-if="uploadVisible">
<div v-if="listType == 'picture-card'">
<LoadingOutlined v-if="loading" />
<UploadOutlined v-else />
<div class="ant-upload-text">{{ text }}</div>
</div>
<a-button v-if="listType == 'picture'" :disabled="disabled">
<UploadOutlined />
{{ text }}
</a-button>
</div>
</a-upload>