用js上传文件到obs里怎么做,有没有大佬又示例的啊,借小弟一览
1条回答
关注 上传文件到 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)”功能。
解决 无用评论 打赏 举报
悬赏问题
- ¥60 版本过低apk如何修改可以兼容新的安卓系统
- ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
- ¥50 有数据,怎么建立模型求影响全要素生产率的因素
- ¥50 有数据,怎么用matlab求全要素生产率
- ¥15 TI的insta-spin例程
- ¥15 完成下列问题完成下列问题
- ¥15 C#算法问题, 不知道怎么处理这个数据的转换
- ¥15 YoloV5 第三方库的版本对照问题
- ¥15 请完成下列相关问题!
- ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?