[英]formData problems using fetch to attempt image upload
我正在嘗試將圖像從 React Native 上傳到服務器。 我對圖像使用了“選擇器”(react-native-document-picker),該部分似乎可以正常工作。 這是我正在使用的代碼:
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
從我的評論中可以看出,FormData 定義之后的“console.log”語句和“.append”語句都是“未定義的”(在“UploadPhoto”函數中)......甚至是“名稱”被設置為未定義的簡單字符串(“圖像上傳”)。 很明顯,整個 FormData 命令完全不起作用。
我花了好幾天時間試圖弄清楚這個……很難相信在 2023 年這樣的事情會如此令人費解。 我以前在從 web 應用程序上傳圖像時遇到過一些困難,但這是我第一次嘗試使用“FormData”並嘗試從 React Native 上傳文件。
任何意見是極大的贊賞。 我提前謝謝你。
要訪問 FormData 中的值,請使用get 。
const data = new FormData();
data.append('name', 'Image Upload');
console.log("data.name is: " + data.get("name"));
上傳文件
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.