vue element 和 antd 上传到七牛云
使用网站
七牛云在线生成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; // 重新抛出错误,以便调用者可以进一步处理
}
}
使用
- ant design vue 通过覆盖默认的上传行为,可以自定义自己的上传实现 customRequest
- element plus 方式为:http-request
- http://baidu.com 为 oss 存储域名
<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>
async function uploadQiniu({ file }) {
initTag.value = false;
const res = await uploadPictureToQiniu(file);
if (res) {
uploadFileList.value.push({
uid: getRandom(10),
name: getFileName(res),
status: 'done',
url: `http://baidu.com/${res}`,
response: {
status: 'history',
message: res,
},
});
let fileUrls = [`http://baidu.com/${res}`];
state.value = fileUrls.join(',');
emit('update:value', fileUrls.join(','));
nextTick(() => {
initTag.value = true;
});
} else {
createMessage.error(`${file.name} 上传失败.`);
}
}