在使用阿里云OSS進行前端直傳時,首先我們需要去阿里云官網注冊自己的存儲桶,然后申請相關的accessKeyId和accessKeySecret,然后新建一個桶,為這個桶命名以及選擇對應的地區(qū)。
然后可以根據自己的業(yè)務,封裝對應的組件,以下是根據我自己的項目,所封裝的上傳組件,所用的是React技術棧文章來源地址http://www.zghlxwxcb.cn/news/detail-833466.html
import OSS from "ali-oss";
import { plus } from '../apis/person/index'
import styles from './oss.module.less'
import { Input } from "antd";
import { useState } from "react";
const Oss = () => {
const [resourcesName, setResourcesName] = useState('')
const upload = () => {
const client = new OSS({
region: "", // 填寫桶的地區(qū)
accessKeyId: "", // 桶的key
accessKeySecret: "", // 桶的secret
bucket: "dd-robot-react", // 桶的名稱
});
const upload = document.getElementById("upload");
async function putObject(data: any) {
try {
const options = {
meta: { temp: "demo" },
mime: "json",
headers: {
"Content-Type": file.type
},
};
const result = await client.put(data.name, data, options)
console.log(result);
console.log(result.url);
const ossDomain = "dd-robot-react.oss-cn-beijing.aliyuncs.com"; // 替換為你的實際OSS域名
const fileUrl = `https://${ossDomain}/${data.name}`;
console.log(fileUrl);
let res = await plus({
data_link: result.url,
data_name: resourcesName,
type: 3
})
console.log(res);
} catch (e) {
console.log(e);
}
}
upload.addEventListener("click", () => {
const data = file.files[0];
console.log(data.name);
putObject(data);
});
}
return (
<>
<input id="file" type="file" className={styles.file} />
<Input
value={resourcesName}
onChange={(e) => setResourcesName(e.target.value)}
placeholder="請輸入文件名"
/>
<button id="upload" onClick={upload} className={styles.btn} style={{ marginTop: 10 }}>上傳資源</button>
</>
)
};
export default Oss;
文章來源:http://www.zghlxwxcb.cn/news/detail-833466.html
到了這里,關于如何使用阿里云OSS進行前端直傳的文章就介紹完了。如果您還想了解更多內容,請在右上角搜索TOY模板網以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網!