用js上传文件到obs里怎么做,有没有大佬又示例的啊,借小弟一览
1条回答 默认 最新
技术探索 2023-06-08 21:40关注上传文件到 OBS 中,可以通过 OBS 提供的 RESTful API 进行调用。在 JavaScript 中,可以使用 Axios 或 Fetch 等库来发送 HTTP 请求。
以下是通过 Axios 实现文件上传的示例代码:
// 引入 axios 库 import axios from 'axios' // 定义 OBS 相关参数 const accessKey = 'access_key' const secretKey = 'secret_key' const bucketName = 'bucket_name' const endpoint = 'obs.myhuaweicloud.com' // 上传文件到 OBS const uploadFile = async (file) => { // 生成请求签名 const date = new Date().toUTCString() const auth = `AWS ${accessKey}:${ crypto .createHmac('sha1', secretKey) .update(`PUT\n\nmultipart/form-data\n${date}\n/${bucketName}/${file.name}`) .digest('base64') }` // 发送 HTTP PUT 请求 const resp = await axios.put(`https://${bucketName}.${endpoint}/${file.name}`, file, { headers: { 'Content-Type': file.type, 'Authorization': auth, 'Date': date } }) // 返回上传结果 return resp.data } // 选取文件并上传 const fileInput = document.createElement('input') fileInput.type = 'file' fileInput.addEventListener('change', async (event) => { const file = event.target.files[0] const result = await uploadFile(file) console.log('Upload result:', result) }) // 添加文件选择框到 DOM 中 document.body.appendChild(fileInput)在上述代码中,首先需要定义 OBS 相关参数,包括 accessKey、secretKey、bucketName 和 endpoint。其中,accessKey 和 secretKey 分别是 OBS 的 Access Key 和 Secret Key,需要在 OBS 控制台上生成;bucketName 是 OBS 用户的 bucket 名称;endpoint 是 OBS API 地址。
在 uploadFile 函数中,先使用 HMAC-SHA1 算法生成请求签名,然后通过 Axios 库发送 PUT 请求来上传文件。在请求头中需要包含签名信息、内容类型和日期。
在 fileInput 的 change 事件中,通过选取文件并调用 uploadFile 函数来上传文件,并输出上传结果。
需要注意的是,如果需要支持跨域上传,需要在 OBS 控制台中开启“跨域资源共享(CORS)”功能。
解决 无用评论 打赏 举报