如何通过Web端直传文件(Object)到OSS
Web端上传OSS介绍
- 用户向应用服务器请求上传Policy和回调。 let params = { "expire": "xxx", "policy": "xxx", "signature": "xxx", "accessid": "xxx", "host": "xxx", "dir": "xxx" }; axios.get(/getOssParams).then(result=>{ params = result.data })
- 应用服务器(nodejs)返回上传Policy和签名给用户。 var dayjs = require(dayjs); var crypto = require(crypto); var nanoid = require(nanoid); var config = { dirPath: "upload/", bucket: "xxx", region: "xxxx", accessKeyId: "xxxx", accessKeySecret: "xxxxx", expAfter: 1000*60*5, // 签名失效时间,毫秒 maxSize: 1024*1000*1024*10, // 文件最大的 size B } // 过期时间 const expire = new Date().getTime() + config.expAfter; const expiration = new Date(expire).toISOString(); const dir = config.dirPath +dayjs().format(YYYY/MM/DD) + "/" + nanoid.nanoid() // 上传文件名 const policyString = JSON.stringify({ expiration, conditions: [ ["content-length-range", 0, config.maxSize], ["starts-with", "$key", dir], ], }); const policy = Buffer.from(policyString).toString("base64"); const signature = crypto .createHmac("sha1", config.accessKeySecret) .update(policy) .digest("base64"); //返回参数 const params = { expire, policy, signature, accessid: config.accessKeyId, host: "https://mukang.net", dir, };
- 用户直接向OSS发送文件上传请求。
const files = document.querySelector(input[type="file"]) var formData = new FormData(); const suffix = files[0].name.slice( files[0].name.lastIndexOf(".") ); const filename = Date.now() + suffix; formData.append("key", params.dir + "/" + filename); formData.append("policy", params.policy); formData.append("OSSAccessKeyId", params.accessid); formData.append("success_action_status", "200"); formData.append("signature", params.signature); formData.append("file", files[0]); axios .post(params.host, formData, { headers: { "Content-Type": "multipart/form-data" }, onUploadProgress: function (progressEvent) { console.log("进度", progressEvent.loaded / progressEvent.total); }, }) .then((result) => { console.log("result.data ===== ", params.hosts + / + params.dir + filename); });
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/291102.html