【问题标题】:Axios response doesn't get executed properlyAxios 响应未正确执行
【发布时间】:2020-09-28 01:42:18
【问题描述】:

我有以下代码,

function FileUpload(props) {

const [Images, setImages] = useState([])

const onDrop = (files) => {

    let formData = new FormData();
    const config = {
        header: { 'content-type': 'multipart/form-data' }
    }
    formData.append("file", files[0])
    //save the Image we chose inside the Node Server 
    Axios.post('/api/product/uploadImage', formData, config)
        .then(response => {
            if (response.data.success) {

                setImages([...Images, response.data.image])
                props.refreshFunction([...Images, response.data.image])

            } else {
                alert('Failed to save the Image in Server')
            }
        })
}

但是,每当我尝试调用 axios 调用并尝试使用我的图像上传器时,我总是会收到“无法将图像保存在服务器中”的不成功消息

这里是 API 调用所指向的地方:

var storage = multer.diskStorage({
destination: (req, file, cb) => {
    cb(null, 'uploads/')
},
filename: (req, file, cb) => {
    cb(null, `${Date.now()}_${file.originalname}`)
},
fileFilter: (req, file, cb) => {
    const ext = path.extname(file.originalname)
    if (ext !== '.jpg' || ext !== '.png') {
        return cb(res.status(400).end('only jpg, png are allowed'), false);
    }
    cb(null, true)
}
})

var upload = multer({ storage: storage }).single("file")


//=================================
//             Product
//=================================

router.post("/uploadImage", auth, (req, res) => {

upload(req, res, err => {
    if (err) {
        return res.json({ success: false, err })
    }
    return res.json({ success: true, image: res.req.file.path, fileName:
    res.req.file.filename })
})

});

有人可以帮我解决为什么图片没有上传吗?

【问题讨论】:

    标签: node.js reactjs file-upload axios


    【解决方案1】:

    可能有很多原因。代码对我来说看起来不错

    • 第一个,因为你期望来自服务器的单个图像文件路径。你可以直接设置它

      setImages(response.data.image)

    • 第二次你创建了上传文件夹,因为图像是由你的节点服务器保存在那里的

    • 第三个文件扩展名必须是这些ext !== '.jpg' || ext !== '.png'

    【讨论】:

    • 谢谢!我真的很愚蠢,我忘了首先创建上传文件夹:(
    • 感谢我的荣幸
    猜你喜欢
    • 2019-01-19
    • 2021-05-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-19
    • 2020-09-15
    • 1970-01-01
    相关资源
    最近更新 更多