# 使用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](https://www.googleapis.com/upload/storage/v1/b/staging.auctionmall-53ad1.appspot.com/o?uploadType=media\&name=photo)>

> AccessToken: ya29.GlzTBUbr5lyXpZV4NSRwV3X9YQsjsmC7rsgOeZrlPJ4Kan4KoR7u5X3PxPBnouJKY99gUuSpwcFX0vTo8pCtVjwMpRxtdvZM7NF2lV52ifjdAKiDpDLwakOzy\_YJvw

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

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

## 使用RNFetchBlob.fetch

* method, `POST, PUT`
* url
* headers
* content
  * wrap 會包裝所在位置的檔案，在native 曾讀入，為得是不影響JS 層
* * 所在位置的檔案必須是base64 encode

```javascript
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)
  );
}
```

常見錯誤：

![](https://3741471281-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LfNCl0-2Tz7pwP50Mpi%2F-LfNCnnzv40pXJQqOOjK%2F-LfNCp6U3oL1TYvc2jSk%2F%E8%9E%A2%E5%B9%95%E5%BF%AB%E7%85%A7%202018-06-05%20%E4%B8%8B%E5%8D%884.42.56.png?generation=1558405666201567\&alt=media)

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

查看有無上傳成功：

[https://zhang699.github.io/gcs\_site/?accessToken=\<AccessToken>](https://zhang699.github.io/gcs_site/?accessToken=ya29.GlzSBc8jMF5cB31JTQbNopFiPt94SNX0UppBIe1uyM0aAJCrzWqjIzx23Mum9nvs4QWWOIg_m8AgpeCmd41N7QHOe7jC51PUBBYTgBPTuAWQ4Vb5qeu0-tlawM_-CQ)

參考資料：

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


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://zhang699-2.gitbook.io/react-native/chapter1_/shi-yong-react-native-fetch-blob-lai-shang-chuan-zhao-pian.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
