您好,我是新来的人,我正在尝试从react本机图像选择器上传图像,但是它没有上传到Node JS服务器,并且图像数据也不会上传到后端Node JS服务器
这是我的本机代码
import React,{useState,useEffect} from 'react'
import {View,Text,StyleSheet,SafeAreaView,TouchableOpacity,Image,Button,AsyncStorage} from 'react-native'
import FontAwesome5 from 'react-native-vector-icons/FontAwesome5';
import ImagePicker from 'react-native-image-picker';
const ActvityScreen = (props) =>
{
const [u_id,setU_id] = useState('');
const [image,setImage] = useState('https://bootdey.com/img/Content/avatar/avatar6.png');
const [filePath,setfilePath] = useState({});
useEffect(() => {
async function fetchData() {
const token = await AsyncStorage.getItem('token');
fetch('http://127.0.0.1:3000',{
headers:new Headers({
Authorization:'Bearer '+token
})
}).then(res=>res.json())
.then(async(data)=>{
// setIsloaded(false);
console.log(data)
setU_id(data.u_id)
setImage('http://127.0.0.1:3000/image/'+data.photoId)
console.log(image)
})
}
fetchData();
}, []);
const handleUploadPhoto = async (filePath) => {
fetch("http://127.0.0.1:3000/updateImageprofile2", {
method: "POST",
body: createFormData(filePath, { userId: u_id }),
headers: {
Accept: 'application/json',
'Content-Type': 'multipart/form-data',
},
})
.then(response => response.json())
.then(response => {
console.log("upload succes", response);
alert("Upload success!");
})
.catch(error => {
console.log("upload error", error);
alert("Upload failed!");
});
};
const createFormData = (photo, body) => {
const data = new FormData();
console.log("photoooooooooooo",photo.fileName);
data.append("photo", {
name: photo.fileName,
type: photo.type,
uri:
Platform.OS === "android" ? photo.uri : photo.uri.replace("file://", "")
});
Object.keys(body).forEach(key => {
data.append(key, body[key]);
});
return data;
};
const chooseFile = () => {
var options = {
title: 'Select Image',
customButtons: [
{ name: 'customOptionKey', title: 'Choose Photo from Custom Option' },
],
storageOptions: {
skipBackup: true,
path: 'images',
},
};
ImagePicker.showImagePicker(options, response => {
console.log('Response = ', response);
if (response.didCancel) {
console.log('User cancelled image picker');
} else if (response.error) {
console.log('ImagePicker Error: ', response.error);
} else if (response.customButton) {
console.log('User tapped custom button: ', response.customButton);
alert(response.customButton);
} else {
let source = response;
setfilePath(source);
handleUploadPhoto(source);
}
});
};
return (
<View style={styles.container1}>
<Image
source={{
uri: 'data:image/jpeg;base64,' + filePath.data,
}}
style={{ width: 100, height: 100 }}
/>
<Image
source={{ uri: filePath.uri }}
style={{ width: 250, height: 250 }}
/>
<Text style={{ alignItems: 'center' }}>
{filePath.uri}
</Text>
<Button title="Choose File" onPress={()=>chooseFile(this)} />
</View>
)
}
const styles = StyleSheet.create({
container1:{
flex:1,
backgroundColor: '#fff',
marginTop:16
},
text:{
color:"#161924",
fontSize:20,
fontWeight: '500'
}
})
export default ActvityScreen;
在这里,当我单击choosefile按钮功能时,它将转到choosefile函数,并且在控制台中图像数据正在显示
这是我的后端代码
const express = require('express');
const mongoose = require('mongoose');
const jwt = require('jsonwebtoken');
const {jwtkey} = require('../keys');
const multer = require('multer');
const router = express.Router();
const GridFsStorage = require('multer-gridfs-storage');
const url = 'mongodb://localhost:27017/pixa';
const storage = new GridFsStorage({ url });
const uploadController = require("../controllers/upload");
const User = mongoose.model('User');
const upload = multer({
dest: "upload/",
});
router.post("/updateImageprofile2", upload.array('photo',3),async (req, res,next) => {
console.log("I am in");
console.log('files', req.files)
console.log('file', req.file)
console.log('body', req.body)
res.status(200).json({
message: 'success!',
})
});
module.exports = router