首页 > 解决方案 > 从反应本机应用程序上传图像后无法将图像保存在我的文件夹中

问题描述

大家好,我正在尝试创建一个带有后端的应用程序,用户可以在其中上传个人资料图片。我在框架 Expressjs 的后面使用 nodejs。但是,当我尝试从我的 react-native 应用程序将图像上传到我的服务器时,没有任何内容会保存到我的图像文件夹中。我现在在iOS上,我不知道它是否会改变任何东西。

当我尝试做同样的事情但没有 react-native 直接使用 Postman 发送 POST 请求时,我能够这样做。我真的不知道为什么我认为它会是扩展名或其他东西,但它并没有改变任何东西。

首先是我的后端代码:我正在使用 Multer 进行上传

const storage = multer.diskStorage({
    destination : function(req, file, cb ){
        cb(null,'./images/');
    },
    filename : function(req,file,cb){
        cb(null, Date.now() + file.originalname);
    }
})
const upload = multer({ storage : storage,
    //filer only valide file == image
fileFilter: function(req,file,cb){
    let ext = path.extname(file.originalname);
    if(ext != '.png' && ext != '.jpg' && ext !='jpeg'){
        return cb('Only images are allowed ')
    }
    cb(null, true)
},
    limits:{fieldSize: 25*1024*1024}
})
// route for photo TEST
router.post('/upload',upload.single('photo'), (req,res)=> {
    console.log('file',req.files);
    //console.log('body', req.body);
    res.status(200).json({
        message:'success!',
    });
});

现在这就是我在我的 react-native 应用程序上所做的

const createFormData = (photo, body) =>{
    const data = new FormData();
    data.append('photo', {
        name:photo.fileName,
        type:photo.type,
        uri : 
        Platform.OS === 'android' ? photo.uri : photo.uri.replace('file://', ''), // to be sure it works with android
    });
    Object.keys(body).forEach(key => {
        data.append(key, body[key]);
    });
    return data;

handleUploadPhoto = () =>{
        fetch('http://localhost:5050/api/new/upload',{
            method: 'POST',
            body: createFormData(this.state.dataPhoto,{userId : 'test'}),
        })
        .then(response => response.json())
        .then(response => {
            console.log('upload succes', response);
            alert('Photo updated succesfully!')
        })
        .catch(error => {
            console.log('upload failed', error);
            alert('Upload is not possible right now!');
        })
    };

我确实收到了警报(“照片在我的屏幕上成功更新”所以我猜它可以在正面工作,但不能在背面工作......我使用 react-native-image-picker 加载图像

我没有收到任何错误消息,但没有文件保存到我的图像文件夹中。提前感谢您的帮助

标签: javascriptnode.jsreact-nativebackend

解决方案


您是否没有看到与您打印的 console.log('file', req.files) 相关的任何内容?

验证上传时,您在节点控制台中获取文件+上传文件相关的对象。

启用控制台正文日志并查看它 console.log('body', req.body)


推荐阅读