()
| 9 | const API_URL = 'http://localhost:1998' |
| 10 | |
| 11 | export default function Home() { |
| 12 | const [file, setFile] = useState<File | null>(null) |
| 13 | const [prisignedGetUrl, setPrisignedGetUrl] = useState("") |
| 14 | const [process, setProcess] = useState(0) |
| 15 | const [tip, setTip] = useState("") |
| 16 | |
| 17 | function generateRandomString() { |
| 18 | const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'; |
| 19 | let result = ''; |
| 20 | for (let i = 0; i < 10; i++) { |
| 21 | result += characters.charAt(Math.floor(Math.random() * characters.length)); |
| 22 | } |
| 23 | return result; |
| 24 | } |
| 25 | |
| 26 | function upload(url: string, file: File, onProgress: (event: ProgressEvent<EventTarget>) => void) { |
| 27 | return new Promise((res, rej) => { |
| 28 | const xhr = new XMLHttpRequest(); |
| 29 | xhr.open('PUT', url); |
| 30 | |
| 31 | xhr.onload = e => { |
| 32 | res("") |
| 33 | }; |
| 34 | xhr.onerror = rej; |
| 35 | if (xhr.upload && onProgress) |
| 36 | xhr.upload.onprogress = onProgress; |
| 37 | xhr.send(file); |
| 38 | }); |
| 39 | } |
| 40 | |
| 41 | useEffect(() => { |
| 42 | if (file === null) return |
| 43 | const uploadFile = async (file: File) => { |
| 44 | const fileName = `${file.name}`.replaceAll( |
| 45 | /[^a-zA-Z0-9.]/g, |
| 46 | "-" |
| 47 | ); |
| 48 | const now = new Date() |
| 49 | const date = `${now.getFullYear()}-${now.getMonth() + 1}-${now.getDate()}-${now.getHours()}` |
| 50 | const objectKey = date + "-" + generateRandomString() + "-" + fileName |
| 51 | const requestUrl = `${API_URL}/presigned-url?key=${objectKey}&content-length=${file.size}&no-wait=5&max-requests=2&expire=1800&limit-rate=5242880&force-download=true` |
| 52 | const response = await fetch(requestUrl) |
| 53 | if (!response.ok) { |
| 54 | console.log("error", response.status) |
| 55 | return |
| 56 | } |
| 57 | |
| 58 | // 获取一个签名的put-url和get-url |
| 59 | const result = await response.json() |
| 60 | const presignedGetUrl = result['get-url'] |
| 61 | const presignedPutUrl = result['put-url'] |
| 62 | setPrisignedGetUrl(presignedGetUrl) |
| 63 | |
| 64 | await upload(presignedPutUrl, file, function (event) { |
| 65 | if (event.lengthComputable) { |
| 66 | setProcess(event.loaded / event.total * 100) |
| 67 | } |
| 68 | }) |
nothing calls this directly
no test coverage detected
searching dependent graphs…