溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

TypeScript前端上傳文件到MinIO怎么實(shí)現(xiàn)

發(fā)布時(shí)間:2022-10-22 14:31:35 來源:億速云 閱讀:281 作者:iii 欄目:web開發(fā)

這篇文章主要講解了“TypeScript前端上傳文件到MinIO怎么實(shí)現(xiàn)”,文中的講解內(nèi)容簡(jiǎn)單清晰,易于學(xué)習(xí)與理解,下面請(qǐng)大家跟著小編的思路慢慢深入,一起來研究和學(xué)習(xí)“TypeScript前端上傳文件到MinIO怎么實(shí)現(xiàn)”吧!

    什么是MinIO?

    MinIO 是一款高性能、分布式的對(duì)象存儲(chǔ)系統(tǒng). 它是一款軟件產(chǎn)品, 可以100%的運(yùn)行在標(biāo)準(zhǔn)硬件。即X86等低成本機(jī)器也能夠很好的運(yùn)行MinIO。

    本地Docker部署測(cè)試服務(wù)器

    docker pull bitnami/minio:latest
    # MINIO_ROOT_USER最少3個(gè)字符
    # MINIO_ROOT_PASSWORD最少8個(gè)字符
    # 第一次運(yùn)行的時(shí)候,服務(wù)會(huì)自動(dòng)關(guān)閉,手動(dòng)再次啟動(dòng)就可以正常運(yùn)行了.
    docker run -itd \
        --name minio-server \
        -p 9000:9000 \
        -p 9001:9001 \
        --env MINIO_ROOT_USER="root" \
        --env MINIO_ROOT_PASSWORD="123456789" \
        --env MINIO_DEFAULT_BUCKETS='images' \
        --env MINIO_FORCE_NEW_KEYS="yes" \
        --env BITNAMI_DEBUG=true \
        bitnami/minio:latest

    上傳的API

    它有3個(gè)API可供調(diào)用:

    • putObject 從流上傳

    • fPutObject 從文件上傳

    • presignedPutObject 提供一個(gè)臨時(shí)的上傳鏈接以供上傳

    使用1和2的方式的話,在前端需要暴露出連接MinIO的訪問密鑰,很不安全,而且官方的Js客戶端壓根就沒想過開放給瀏覽器.
    而3的話,可以由服務(wù)端生成一個(gè)臨時(shí)的上傳鏈接提供給前端上傳之用,而無需要暴露訪問MinIO的密鑰,非常的安全,我采用的是第三種方式.

    TypeScript實(shí)現(xiàn)

    在TypeScript下,我們可用的有三種方式實(shí)現(xiàn)文件上傳:

    • XMLHttpRequest

    • Fetch API

    • Axios

    需要注意的是: 事實(shí)上,后兩種API都是封裝的XMLHttpRequest.

    1. XMLHttpRequest

    function xhrUploadFile(file: File, url: string) {
      const xhr = new XMLHttpRequest();
      xhr.open('PUT', url, true);
      xhr.send(file);
      xhr.onload = () => {
        if (xhr.status === 200) {
          console.log(`${file.name} 上傳成功`);
        } else {
          console.error(`${file.name} 上傳失敗`);
        }
      };
    }

    2. Fetch API

    function fetchUploadFile(file: File, url: string) {
      fetch(url, {
        method: 'PUT',
        body: file,
      })
        .then((response) => {
          console.log(`${file.name} 上傳成功`, response);
        })
        .catch((error) => {
          console.error(`${file.name} 上傳失敗`, error);
        });
    }

    3. Axios

    function axiosUploadFile(file: File, url: string) {
      const instance = axios.create();
      instance
        .put(url, file, {
          headers: {
            'Content-Type': file.type,
          },
        })
        .then(function (response) {
          console.log(`${file.name} 上傳成功`, response);
        })
        .catch(function (error) {
          console.error(`${file.name} 上傳失敗`, error);
        });
    }

    從后端獲取臨時(shí)上傳鏈接

    function retrieveNewURL(file: File, cb: (file: File, url: string) => void) {
      const url = `http://localhost:8080/presignedUrl/${file.name}`;
      axios.get(url)
        .then(function (response) {
          cb(file, response.data.data.url);
        })
        .catch(function (error) {
          console.error(error);
        });
    }

    上傳文件

    function onXhrUploadFile(file?: File) {
      console.log('onXhrUploadFile', file);
      if (file) {
        retrieveNewURL(file, (file, url) => {
          xhrUploadFile(file, url);
        });
      }
    }

    踩過的坑

    1. presignedPutObject方式上傳提交的方法必須得是PUT

    我試過了用POST去上傳文件,但是顯然的是:我失敗了.必須得用PUT去上傳.

    2. 直接發(fā)送File即可

    看了不少文章都是這么干的: 構(gòu)造一個(gè)FormData,然后把文件打進(jìn)去,如果用putObjectfPutObject這兩種方式上傳,這是沒問題的,但是使用presignedPutObject則是不行的,直接發(fā)送File就可以了.

    fileUpload(file) {
        const url = 'http://example.com/file-upload';
        const formData = new FormData();
        formData.append('file', file)
        const config = {
            headers: {
                'content-type': 'multipart/form-data'
            }
        }
        return  post(url, formData,config)
    }

    如果使用以上的方式上傳,文件頭會(huì)被插入一段數(shù)據(jù),看起來像是這樣子的:

    ------WebKitFormBoundaryaym16ehT29q60rUx
    Content-Disposition: form-data; 
    name="file"; 
    filename="webfonts.zip"
    Content-Type: application/zip

    它是遵照了 rfc1867 定義的協(xié)議.

    3. 使用Axios上傳的時(shí)候,需要自己把Content-Type填寫成為file.type

    直接使用XMLHttpRequestFetch API都會(huì)自動(dòng)填寫成為文件真實(shí)的Content-Type.而Axios則不會(huì),需要自己填寫進(jìn)去,或許是我不會(huì)使用Axios,但是這是一個(gè)需要注意的地方,否則在MinIO里邊的Content-Type會(huì)被填寫成為Axios默認(rèn)的Content-Type,或者是你自己指定的.

    感謝各位的閱讀,以上就是“TypeScript前端上傳文件到MinIO怎么實(shí)現(xiàn)”的內(nèi)容了,經(jīng)過本文的學(xué)習(xí)后,相信大家對(duì)TypeScript前端上傳文件到MinIO怎么實(shí)現(xiàn)這一問題有了更深刻的體會(huì),具體使用情況還需要大家實(shí)踐驗(yàn)證。這里是億速云,小編將為大家推送更多相關(guān)知識(shí)點(diǎn)的文章,歡迎關(guān)注!

    向AI問一下細(xì)節(jié)

    免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

    AI