Created
April 15, 2022 07:23
-
-
Save HERYORDEJY/4e644d67d5d7bf2bef0d5fcd96c584a2 to your computer and use it in GitHub Desktop.
React Native FormData file upload issue.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import { AxiosRequestConfig } from "axios"; | |
| const FormData = global.FormData; | |
| const axiosInstance = axios.create({ | |
| baseURL: 'example.com', // use with scheme | |
| timeout: 30000, | |
| headers: { | |
| "X-Platform": 'iOS', | |
| "X-App-Build-Number": '1.0.0', | |
| }, | |
| }); | |
| const formData = new FormData(); | |
| formData.append("userId", "123456"); | |
| formData.append("file", { | |
| uri: "/dev/sda/abc.png", | |
| type: "image/png", | |
| name: "abc.png", | |
| }); | |
| const config: AxiosRequestConfig = { | |
| method: "post", | |
| url: "/process/start", | |
| responseType: "json", | |
| headers: { | |
| 'Content-Type': 'multipart/form-data', | |
| // if backend supports u can use gzip request encoding | |
| // "Content-Encoding": "gzip", | |
| }, | |
| transformRequest: (data, headers) => { | |
| // !!! override data to return formData | |
| // since axios converts that to string | |
| return formData; | |
| }, | |
| onUploadProgress: (progressEvent) => { | |
| // use upload data, since it's an upload progress | |
| // iOS: {"isTrusted": false, "lengthComputable": true, "loaded": 123, "total": 98902} | |
| }, | |
| data: formData, | |
| }; | |
| // send post request and get response | |
| const response = await axiosInstance.request(config); |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
12
when you are using react-native you don't need "form-data" package. Because react native polyfills standard FormData api and exports it as global.
second problem is axios converts form data automatically to string, so you need to use transformRequest config on request to override it.