先贴个github链接(私有链接)COS-Case
主要思路:前端接受文件后,向后端获取签名,然后直接传入COS
前端
import {Button, Upload} from "antd";
import {UploadOutlined} from '@ant-design/icons';
import {getAuthorization} from "../../request";
import COS from "cos-js-sdk-v5";
import {useEffect, useState} from "react";
const prop = {
Bucket: 'test-1111111',//桶名称
Region: 'ap-shanghai',//桶地域
Key: '1.jpg',
Body: null,
}
const FileItem = () => {
const [cos, setCos] = useState({})
useEffect(() => {
let cos = new COS({
getAuthorization: async function (options, callback) {
// 获取认证
let res = await getAuthorization()
console.log(res)
callback({
TmpSecretId: res.secrectId, //密钥id
TmpSecretKey: res.secretKey, // 密钥
SecurityToken: "eybToken", // token
StartTime: res.startTime, // 开始时间,时间戳,最好用服务器时间
ExpiredTime: res.expireTime, // 截止时间,时间戳
})
}
})
setCos(cos)
}, [])
const beforeUpload = async (e) => {
console.log(e)
prop.Body = e
//上传文件
let data = await cos.uploadFile(prop)
console.log(data)
return false
}
const downloadFile = () => {
cos.getObjectUrl(prop,(err,data)=>{
if(err) return console.log(err)
console.log(data)
//response-content-disposition=attachment 用于指定以什么样的格式打开,attachment即附件
let downLoadUrl = data.Url+(data.Url.indexOf('?')>-1?'&':'?') + 'response-content-disposition=attachment'
//是否重命名
downLoadUrl +=';filename=myname.jpg'
window.open(downLoadUrl)
})
}
const props = {
name: '',
action: '', //上传的地址
headers: {
authorization: 'authorization-text',
},
beforeUpload,
}
return (
<>
<Upload {...props} >
<Button icon={<UploadOutlined/>}>Click to Upload</Button>
</Upload>
<Button onClick={downloadFile}>
Click to DownLoad File
</Button>
</>
)
}
export default FileItem
后端
package services
import (
"github.com/gin-gonic/gin"
"time"
)
type Secret struct {
SECRECTID string `json:"secrectId"`
SECRETKEY string `json:"secretKey"`
STARTTIME int64 `json:"startTime"`
EXPIRETIME int64 `json:"expireTime"`
}
type Response struct {
Code string `json:"code"`
Data interface{} `json:"data"`
Message string `json:"message"`
}
const SECRECTID string = "111" //你的腾讯云secretId
const SECRETKEY string = "222" //你的腾讯云secretKey
func GetAuthorization(cilent *gin.Context) {
s := Secret{SECRECTID: SECRECTID, SECRETKEY: SECRETKEY, STARTTIME: time.Now().Unix(), EXPIRETIME: time.Now().Add(time.Second * 60).Unix()}
cilent.Header("Access-Control-Allow-Origin", "*")
cilent.JSON(200, Response{
Code: "0",
Data: s,
Message: "successful",
})
return
}
Q.E.D.