这是我的前端:
import React from 'react';
import {StyleSheet, Text, View, TouchableHighlight } from 'react-native';
import {launchImageLibrary} from 'react-native-image-picker';
const App = () => {
const [photo, setPhoto] = React.useState(null);
const handleChoosePhoto = () => {
launchImageLibrary({ maxHeight:300, maxWidth:300 }, (response) => {
// console.log(response);
if (response) {
setPhoto(response);
}
});
};
const handleUploadPhoto = () => {
const data = new FormData();
data.append('photo', {
name: photo.fileName,
type: photo.type,
uri: photo.uri,
});
console.log(data);
fetch('http://172.20.10.2:5000/upload_profile_picture/', {
method: 'POST',
headers : {
'Accept' : 'application/json',
'Content-Type' : 'multipart/form-data'
},
body: data
// body : JSON.stringify({ userId: '123' })
})
.then((response) => response.json())
.then((response) => {
console.log('response', response);
})
.catch((error) => {
console.log('error', error);
});
};
return (
<View style={styles.container}>
<TouchableHighlight
onPress={handleChoosePhoto}
>
<Text>Choose image</Text>
</TouchableHighlight>
<TouchableHighlight onPress={handleUploadPhoto}>
<Text>Upload Image</Text>
</TouchableHighlight>
</View>
);
};
const styles = StyleSheet.create({
container : {
flex:1,
justifyContent:"center",
alignItems:"center"
}
});
export default App;
这是我的后端:
const express = require("express");
const app = express();
const jwt = require('jsonwebtoken');
require("./conn");
const multer = require('multer');
const members = require("./models/members");
const bcrypt = require("bcryptjs");
const PORT = process.env.PORT || 5000;
app.use(express.json());
const storage = multer.diskStorage({
destination: (req, file, callback) => {
callback(null, './images/');
},
filename: (req, file, callback) => {
callback(null, `${file.fieldname}_${Date.now()}_${file.originalname}`);
},
});
const upload = multer({ storage }).single('file');
app.post("/upload_profile_picture", upload, (req, res) => {
console.log('file', req.file);
console.log('body', req.body);
res.status(200).json({
message: 'success!',
});
});
app.listen(PORT, () => {
console.log("Port is working.");
})
我在本机终端中得到这个输出:
{"_parts": [["photo", [Object]]]}
LOG error [TypeError: Network request failed]
但是在 nodeJs(Express Server)中什么也没有
我没有找到任何关于此的教程或 YouTube 视频。或者,如果您可以使用 "React-native-image-crop-picker" 做到这一点,一切都会好起来的。提前致谢。