<template> <div> <input type="file" @change="handleFileChange" /> <button @click="uploadFile">上传</button> </div> </template> <script> import axios from 'axios'; import { getQiNiuToken } from '@/utils/auth' export default { data() { return { selectedFile: null, uploadToken: null, }; }, created() { this.getUploadToken(); // 获取上传凭证 }, methods: { async getUploadToken() { try { const res = await getQiNiuToken(); // 调用封装的接口方法 console.log('获取上传凭证:', res); if (res && res.data && res.data.qny_token ) { this.uploadToken = res.data.qny_token ; // 将获取到的 Token 保存 console.log('获取上传凭证成功:', this.uploadToken); } else { console.error('获取上传凭证失败:返回数据格式不正确', res); } } catch (error) { console.error('获取上传凭证失败:', error); } }, async handleFileChange(event) { this.selectedFile = event.target.files[0]; }, async uploadFile() { if (!this.selectedFile) { alert('请先选择文件!'); return; } try { // 获取七牛云上传凭证 const token = this.uploadToken; console.log('七牛云上传凭证:', token); // 七牛云上传地址(这里需要您根据实际情况填写) const uploadUrl = 'https://up-z2.qiniup.com/blog_cdn'; // 替换为您的Bucket域名 // 创建FormData对象,用于存储要上传的文件和其他参数 const formData = new FormData(); formData.append('file', this.selectedFile); formData.append('token', token); // 发送文件上传请求 const uploadResponse = await axios.post(uploadUrl, formData, { headers: { 'Content-Type': 'multipart/form-data', }, }); // 处理上传响应 console.log('上传成功:', uploadResponse.data); alert('文件上传成功!'); } catch (error) { console.error('上传失败:', error); alert('文件上传失败,请重试!'); } }, }, }; </script>
其中getQiNiuToken为后端提供的七牛云token
// 获取七牛云token export function getQiNiuToken() { return request({ url: '/qiniu/get-token/', method: 'post' }) }
后端提供七牛云token
##七牛云前端上传凭证-vue from qiniu import Auth from rest_framework.viewsets import GenericViewSet from rest_framework.permissions import IsAuthenticated from rest_framework.decorators import action access_key = settings.QINIU_ACCESS_KEY secret_key = settings.QINIU_SECRET_KEY bucket_name = settings.QINIU_BUCKET_NAME class QiniuTokenViewSet(GenericViewSet): """ ViewSet 用于获取七牛云 Token """ permission_classes = [IsAuthenticated] # 仅认证用户可访问 @action(detail=False, methods=['post'], url_path='get-token') def get_qiniu_token(self, request): try: q = Auth(access_key, secret_key) token = q.upload_token(bucket_name, expires=3600) return Response({"qny_token": token}) except Exception as e: return Response({"error": "cdn token error", "status": 500, "detail": str(e)})
以上是上传最简易版本
版权声明:如无特殊说明,文章均为本站原创,转载请注明出处
本文链接:http://kkxl95.cn/article/bdISjPqK2WVuzQNyes36/