如何仅发送文件名以响应多个文件上传

how to send just the filename in response of multer file upload

嗨,我正在使用 express 和 multer 从反应前端接收后端的多个文件,我的反应查询代码是这样的:

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

​

一切就绪,只需使用 Axios 响应中的 data 属性 object。

console.log(r.data.names)

Axios returns 响应 object 不仅包含响应 body。您将获得状态、headers、配置、请求。完整的字段列表在 Axios docs.

中可用

此外,还有一些旁注。你不想在 React 中设置 'Content-Type': 'application/json',因为你使用的是 FormData - 它会在幕后设置 'Content-Type': 'multipart/form-data'。在 Express 中,如果您使用 res.json(),则根本不必设置内容类型,因为该函数已经设置了它。