使用 multer 发送状态和文件

Sending state and files with multer

我想在 multer 中发送带有文件的数据。从 React app 到 node server so,

构造函数(道具){ 超级(道具)

    this.state = {
        error:false,
        isProcessing:false,
        isPassed:false,
        isFaild:false,
        errorLine:'',
        data:'something'
    }

    this.handleChoose = this.handleChoose.bind(this)
}
handleChoose(e){
    const fd = new FormData()
    console.log(e.target.files)
    fd.append('file',e.target.files[0],e.target.files[0].name)
    fd = Object.assign({},fd,this.state)
    console.log(fd)
    axios.post(`/api/${this.state.area}`,fd)
                    .then((res)=>{
                        this.setState({"isPassed":true})
                    })
                    .catch((e)=>{
                        if(e){
                            console.log(e.response)
                            this.setState({'isProcessing':false,
                                                        'errorLine':e.response.data.error})
                        }
                    })
}                        

这给我带来了错误 fd 是只读的 所以我搜索并找到

    fd.append('file',e.target.files[0],e.target.files[0].name)
    fd.append('state',this.state)
    console.log(fd)
    axios.post(`/api/${this.state.area}`,fd)
                    .then((res)=>{
                        this.setState({"isPassed":true})
                    })
                    .catch((e)=>{
                        if(e){
                            console.log(e.response)
                            this.setState({'isProcessing':false,
                                                        'errorLine':e.response.data.error})
                        }
                    })

但是当我在服务器上打印时。

router.post('/somethin',upload,userVerifyMiddleWare,(reqs,resp)=>{
    console.log(reqs.body.state.data)
})

它显示 undefined 作为输出。但是我得到了 reqs.files 所需的输出。

const upload =multer({storage: multer.diskStorage({
    destination: function (req, file, callback) { callback(null, './temp/');},
    filename: function (req, file, callback) { callback(null, file.fieldname + '-' + Date.now()+'.csv');}})
}).single('file');

是多个对象。

Error fd is read only 是因为你将formData变量fd声明为const引起的,改成let就可以解决问题

我找到了解决这个问题的方法。其实我不知道发送对象的方式,但是我们可以解决问题

fd.append('file',e.target.files[0],e.target.files[0].name)
fd.append('state-value-1',this.state.value1)
fd.append('state-value-2',this.state.value2)

在服务器上我们可以

console.log(req.body) // to get all non file values
console.log(req.file) // for file