【发布时间】:2021-09-02 07:51:35
【问题描述】:
我没有在服务器端接收数据。有时我将数据作为对象。我尝试了不同的方法,但图像上传失败。下面是我的代码。我尝试了不同的方法,但结果是相同的图像文件夹仍然为空,因为我使用 multer 中间件
图像正在使用这个 sn-p 显示
<TouchableHighlight
style={[
styles.profileImgContainer,
{ borderColor: "#4632a1", borderWidth: 1 },
]}
onPress={openImagePickerAsync}
>
<Image source={{ uri: selectedImage.localUri }} style={styles.thumbnail} />
</TouchableHighlight>
这是图像选择器部分
function PickImage() {
let [selectedImage, setSelectedImage] = useState("");
let openImagePickerAsync = async () => {
let permissionResult =
await ImagePicker.requestMediaLibraryPermissionsAsync();
if (permissionResult.granted === false) {
alert("Permission to access camera roll is required!");
return;
}
let pickerResult = await ImagePicker.launchImageLibraryAsync();
if (pickerResult.cancelled === true) {
return;
}
setSelectedImage({ localUri: pickerResult.uri });
};
}
获取 API 调用
async function upload() {
const data = new FormData();
data.append("image", {
uri: selectedImage.uri,
name: selectedImage.title,
type: selectedImage.type,
});
const setting = {
method: "POST",
headers: {
"Content-Type": "multipart/form-data;",
},
body: data,
};
try {
const fetchResponse = await fetch(url, setting);
const data = await fetchResponse.json();
alert(data);
} catch (e) {
alert(e);
}
}
服务器端代码
app.post("/users", upload.single("image"), async (req, res) => {
console.log(req.body.file);
console.log(req.body);
const img = req.body.image;
if (!img) {
console.log("no image");
}
res.send({ congrats: "data recieved" });
});
【问题讨论】:
标签: react-native express expo multer