[英]formData problems using fetch to attempt image upload
I am attempting to upload an image from React Native to a server.我正在尝试将图像从 React Native 上传到服务器。 I have used a 'picker' (react-native-document-picker) to select the image and that part seems to be functional.
我对图像使用了“选择器”(react-native-document-picker),该部分似乎可以正常工作。 Here is the code I am working with:
这是我正在使用的代码:
import React, { Component } from "react";
import { Button, Dimensions, Image, Platform, SafeAreaView, ScrollView, StyleSheet, Text, TextInput, TouchableOpacity, View } from "react-native";
import DocumentPicker from 'react-native-document-picker';
const SERVER_URL = 'http://localhost:3000';
export default class Images extends Component {
constructor(props) {
super(props);
this.state = {
photo: null,
};
}
ChoosePhoto = async () => {
try {
const res = await DocumentPicker.pickSingle({ type: [DocumentPicker.types.images], });
this.setState({ photo: res }); //Set the state to the selected file attributes
} catch (err) {
this.setState({ photo: null });
if (DocumentPicker.isCancel(err)) {
alert('Canceled'); //user canceled the document selection
} else {
alert('Selection Error: ' + JSON.stringify(err)); //Unknown Error
} //Handling any exception (if any)
} //try routine
};
UploadPhoto = async () => {
if (this.state.photo != null) {
//if file selected then create FormData
const fileToUpload = this.state.photo.uri;
const data = new FormData();
data.append('name', 'Image Upload');
data.append('type', this.state.photo.type);
data.append('file_attachment', fileToUpload);
console.log("data.name is: " + data.name); //"undefined"
console.log("data.type is: " + data.type); //"undefined"
console.log("data.file_attachment is: " + data.file_attachment); //"undefined"
console.log("fileToUpload is: " + fileToUpload); //correct
//****UPLOAD TO SERVER
fetch(`${SERVER_URL}/api/upload`, {
method: 'POST',
body: data,
headers: { 'Content-Type': 'multipart/form-data' }
})
.then((response) => response.json())
.then((response) => {
console.log('Upload success: ', response);
alert('Upload success!');
this.setState({ photo: null });
})
.catch((error) => {
this.setState({ photo: null });
this.setState({ notify: "Pending Upload..." });
console.log('Upload error: ', error);
alert('Upload failed!');
});
//****
} else {
alert('Please Select File to Upload...');
} //'this.state.photo' is NOT NULL...OR NOT...
};
...
} //class 'Images' Component
As can be seen in my comments, the 'console.log' statements following the definition of the FormData and the '.append' statements are all "undefined" (in the 'UploadPhoto' function)...even the 'name' which was set to a simple string ('Image Upload') is not defined.从我的评论中可以看出,FormData 定义之后的“console.log”语句和“.append”语句都是“未定义的”(在“UploadPhoto”函数中)......甚至是“名称”被设置为未定义的简单字符串(“图像上传”)。 So obviously the entire FormData command is totally non-functional.
很明显,整个 FormData 命令完全不起作用。
I have spent days trying to figure this...difficult to believe in 2023 something like this should be so convoluted.我花了好几天时间试图弄清楚这个……很难相信在 2023 年这样的事情会如此令人费解。 I have previously had little difficulty uploading images from web applications before however this is my first attempt at using 'FormData' and attempting a file upload from React Native.
我以前在从 web 应用程序上传图像时遇到过一些困难,但这是我第一次尝试使用“FormData”并尝试从 React Native 上传文件。
Any advice is greatly appreciated.任何意见是极大的赞赏。 I thank you in advance.
我提前谢谢你。
To access values in FormData use get .要访问 FormData 中的值,请使用get 。
const data = new FormData();
data.append('name', 'Image Upload');
console.log("data.name is: " + data.get("name"));
To upload a file上传文件
const body = new FormData()
body.append('file', {uri: 'path/to/content', type: 'type', name: 'name'})
const response = await fetch('url', {
method: 'POST',
headers: {
'Content-Type': 'multipart/form-data',
},
body: body
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.