使用react-native-fetch-blob 來上傳照片

使用Google Cloud Storage 作為測試上傳的API

API EndPoint, POST: https://www.googleapis.com/upload/storage/v1/b/staging.auctionmall-53ad1.appspot.com/o?uploadType=media&name=<your name here>

AccessToken: ya29.GlzTBUbr5lyXpZV4NSRwV3X9YQsjsmC7rsgOeZrlPJ4Kan4KoR7u5X3PxPBnouJKY99gUuSpwcFX0vTo8pCtVjwMpRxtdvZM7NF2lV52ifjdAKiDpDLwakOzy_YJvw

使用uuid作為名字欄位,讓檔名不重複

https://www.googleapis.com/upload/storage/v1/b/staging.auctionmall-53ad1.appspot.com/o?uploadType=media&name=<uuid>

使用RNFetchBlob.fetch

  • method, POST, PUT

  • url

  • headers

  • content

    • wrap 會包裝所在位置的檔案,在native 曾讀入,為得是不影響JS 層

    • 所在位置的檔案必須是base64 encode

import RNFetchBlob from 'react-native-fetch-blob'
...


async fetch(){
    const result = await RNFetchBlob.fetch(
      'POST',
      `https://www.googleapis.com/upload/storage/v1/b/staging.auctionmall-53ad1.appspot.com/o?uploadType=media&name=${new Date().getTime()}`,
      {
        Authorization:
          'Bearer <AccessToken>'
      },
      RNFetchBlob.wrap(uri)
  );
}

常見錯誤:

原因:尚未 react-native link 並重裝app

查看有無上傳成功:

https://zhang699.github.io/gcs_site/?accessToken=<AccessToken>

參考資料:

https://github.com/joltup/react-native-fetch-blob

Last updated