React native 使用multer将本机映像上载到节点服务器
经过数周的努力,我想在放弃之前寻求帮助 当邮递员发送图像并将其存储在服务器中时,节点端点工作正常。请参阅下面的服务器代码:React native 使用multer将本机映像上载到节点服务器,react-native,expo,multer,form-data,React Native,Expo,Multer,Form Data,经过数周的努力,我想在放弃之前寻求帮助 当邮递员发送图像并将其存储在服务器中时,节点端点工作正常。请参阅下面的服务器代码: const multer = require('../helpers/multer'); const upload = multer(config.imagesUrl); module.exports = function(app){ app.post('/species', // ... upload.single('imag
const multer = require('../helpers/multer');
const upload = multer(config.imagesUrl);
module.exports = function(app){
app.post('/species',
// ...
upload.single('image'),
// ...
);
但我无法从我的React本机应用程序中实现这一点。请参阅下面的应用程序代码
import * as ImagePicker from 'expo-image-picker';
export default function AddUser({ navigation }) {
const [user, setUser] = useState(null);
const pickImage = async () => {
let result = await ImagePicker.launchImageLibraryAsync({
mediaTypes: ImagePicker.MediaTypeOptions.All,
allowsEditing: true,
aspect: [4, 3],
quality: 1,
});
if (!result.cancelled) {
setUser({'image', result.uri});
}
};
function onSubmit(){
let formData = new FormData();
formData.append('name', user.name);
formData.append('groupId', user.group);
// Infer the type of the image
if(user.image){
let fileName = user.image.split('/').pop();
let match = /\.(\w+)$/.exec(fileName);
let fileType = match ? `image/${match[1]}` : `image`;
formData.append('image', {
uri: Platform.OS === 'android' ? user.image : user.image.replace('file://', ''),
name: user.name,
type: fileType,
});
}
axios.post(backend.url + '/user', formData, {
headers: {
Accept: "application/json",
"Content-Type": "multipart/form-data"
}
})
.then(res => {
console.log('SUCCESS');
// ...
})
.catch(err => {
console.log('ERROR');
// ...
});
}
return (
// ...
{ user.image && <Image source={{ uri: user.image }} style={{ width: 200, height: 200 }} /> }
<Button onPress={pickImage} >Pick an image</Button>
<Button onPress={onSubmit} >Send</Button>
//..
);
}
所有其他应用程序调用都使用axios运行,并且已经实现了默认凭据/头。我希望避免更改为rn fetch blob或fetch
知道少了什么吗?我没能让它工作。我找到了使用base64的可能性。 这很好地解释了这一点。
我使用了body解析器,但忘记了表单数据和multer 是否尝试调试正在发送的内容?在“网络”选项卡中,您应该检查是否以二进制格式发送。@anthonywillismuñoz在“反应本机调试器网络”选项卡中,我可以看到表单数据以及其中的元素。图像是“图像:[对象]”。我不认为它意味着二进制
[Object: null prototype] {
name: 'Joe',
groupId: '5e8cdd3b8296523464c7462d',
image: '[object Object]' }