【问题标题】:Upload image file to server node.js express axios上传图片文件到服务器node.js express axios
【发布时间】:2018-05-17 18:38:24
【问题描述】:

我一直在尝试上传图像文件并将其保存到我的后端。我正在使用 axios 从反应前端调用 express API。

前端在端口 3000 上运行 后端运行端口 8080

export function updateSociete(data){
return dispatch => {
    // Init loading...
    dispatch(setLoading()) 

    console.log(data) // File data is populated
    axios.post(`${API_ENDPOINT}api/societe/update`, 
        { 
            data: data,
        },
        { headers: {
            'Content-Type': 'Application/json',
            'x-access-token': localStorage.getItem('token')
        }
    })
    .then(function (response) {  
        return response.data
    }) 
    .then( societe => {
        // do something
    })
}

还有快递后台

router.post('/update', (req, res, next) => {
    var data = req.body;

    console.log(data) // No file data here 

如果我尝试将标头设置为 multipart/form-data,我仍然有空数据。当axios向后端发送数据对象时发生了一些事情,后端接收到正常的数据期望文件数据。

使用邮递员进行测试时,我收到所有数据文件等。

【问题讨论】:

    标签: reactjs file express upload axios


    【解决方案1】:

    你可以把它转换成formData。

    你可以试试下一个:

    export function updateSociete(data){  
     return dispatch => {  
     // Init loading...  
     dispatch(setLoading())   
    
     console.log(data) // File data is populated
     const formData = new FormData(data) 
     axios.post(`${API_ENDPOINT}api/societe/update`, 
        { 
            data: formData,
        },
        { headers: {
            'Content-Type': 'Application/json',
            'x-access-token': localStorage.getItem('token')
        }
     })
     .then(function (response) {  
        return response.data
     }) 
     .then( societe => {
        // do something
     })
    }
    

    P.S:确保你有这个
    <form onSubmit={you upload function logic}> .... </form>

    在Using_FormData_Objects 了解更多

    【讨论】:

    • 现在,我只是将文件转换为base64,然后将其发送到DB。
    • 太棒了!但这会将图像存储在服务器本身!
    • 图片还应该存放在哪里?
    猜你喜欢
    • 1970-01-01
    • 2018-08-27
    • 2019-05-16
    • 2014-10-01
    • 2011-06-01
    相关资源
    最近更新 更多