嗨,我正在使用express和multer从react前端接收后端的多个文件,我的react查询代码是这样的:
fileChangeHandler = (event) => {
const data = new FormData()
let files = event.target.files
for (let file of files) {
data.append('file', file)
}
let url = db.url + "/adminendpoint/uploadfile"
axios.post(url, data, {
headers: {
'Content-Type': 'application/json',
Authorization: this.props.token
},
}).then(r => console.log(r.names))
}
multer的后端数据如下:
uploadFile = async (req,res,next)=>{
let storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'public/images')
},
filename: function (req, file, cb) {
cb(null, Date.now() + '-' +file.originalname )
}
})
let upload = multer({storage:storage}).array('file')
upload(req, res, function (err) {
if (err instanceof multer.MulterError) {
return res.json({err:err})
} else if (err) {
return res.json({err:err})
}
let names=[]
req.files.map(f=> names.push(f.filename))
console.log(names);
res.setHeader('Content-Type', 'application/json');
return res.json({names:names})
})
但是很奇怪的是,在后端,名称是一个数组,用于保存上载文件的名称,但是在前端,响应是一个具有大量数据的对象,像这样。它具有名称数组,但我想停止从后端发送此数据块,而仅发送文件名,并且响应格式应仅为json
config: {url: "http://localhost:8090/adminendpoint/uploadfile", method: "post", data: FormData, headers: {…}, transformRequest: Array(1), …}
data:
names: (2) ["1603483842517-2.png", "1603483842518-3.png"]
__proto__: Object
headers: {content-length: "54", content-type: "application/json; charset=utf-8"}
request: XMLHttpRequest {readyState: 4, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, onreadystatechange: ƒ, …}
status: 200
statusText: "OK"
__proto__: Object
答案 0 :(得分:1)
一切就绪,只需使用Axios响应对象中的data
属性即可。
console.log(r.data.names)
Axios返回一个响应对象,该对象不仅包含响应主体。您将获得状态,标题,配置,请求。完整的字段列表在Axios docs中可用。
还有一些注意事项。您不想在React中设置'Content-Type':'application / json',因为您正在使用FormData-它会在幕后设置'Content-Type':'multipart / form-data'。在Express中,如果您使用的是res.json()
,则不必设置任何内容类型,因为该功能已经设置了它。