【问题标题】:how to send just the filename in response of multer file upload如何仅发送文件名以响应 multer 文件上传
【发布时间】:2021-02-06 21:58:46
【问题描述】:

嗨,我正在使用 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

​

【问题讨论】:

    标签: node.js json reactjs multer


    【解决方案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(),则根本不需要设置内容类型,因为该功能已经设置了它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-04
      • 2021-07-10
      • 2023-03-12
      • 2022-07-08
      • 2018-11-01
      • 2018-07-21
      • 2018-02-25
      • 2016-05-22
      相关资源
      最近更新 更多