【问题标题】:How to handle multiple uploads in Hapi.js如何在 Hapi.js 中处理多个上传
【发布时间】:2017-07-27 01:49:11
【问题描述】:

提交多个上传时,以下 index.js 可以正常工作 与:

curl http://localhost:4000/upload -F 'files=@data/file1.txt' -F
'files=@data/file2.txt'

但是如果只提交一个文件就会失败:

curl http://localhost:4000/upload -F 'files=@data/file1.txt'

因为 hapi 期望 files 是一个数组。

如果我改用files[],它也不起作用,那就是

curl http://localhost:4000/upload -F 'files[]=@data/file1.txt'

如果files 是一个数组,我可以通过检查index.js 来解决这个问题,如果不是,我就用 [files] 包装它,这样剩下的代码就不会了t break 但我觉得解决方案不是那么优雅。这是 hapi.js 文件上传处理中的限制/错误吗?

/* index.js */
const Hapi = require('hapi')
const server = new Hapi.Server()
server.connection({
    port:4000
})

const routes = [
    {
        path: '/upload',
        method: 'POST',
        config: {
            payload: {
                output: 'stream',
                parse: true,
                allow: 'multipart/form-data'
            }
        },
        handler: function(request, reply) {
            const p = request.payload, files = p.files
            if(files) {
                console.log(`${files.length} files`)
                files.forEach(function(file) {
                    // do something with file here
                })
            }
            return reply({result: 'ok'})
        }
    }
]

server.route(routes)

server.start(function() {
    console.log(`server started at ${server.info.uri}`)
})

【问题讨论】:

    标签: bash curl file-upload hapi.js


    【解决方案1】:

    事实上,Hapi 无法判断 files 元素是否是一个数组,除非它可以从请求中的多次使用中推断出它。

    您应该能够通过添加Joi 有效负载验证来告诉 Hapi 如何明确解释它。比如:

    config: {
        payload: {
            output: 'stream',
            parse: true,
            allow: 'multipart/form-data'
        },
        validate: {
            payload: Joi.object({
                files: Joi.array().single()
            })
        }
    },
    

    【讨论】:

    • 不知道 single(),很好的用例。我已经用你的建议进行了测试,它就像一个魅力。谢谢。
    【解决方案2】:

    我刚刚发现使用这种技术确保文件始终是一个数组实际上非常容易:

    const p = request.payload, files = [].concat(p.files)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-07-17
      • 1970-01-01
      • 1970-01-01
      • 2014-10-30
      • 1970-01-01
      • 1970-01-01
      • 2015-10-04
      • 1970-01-01
      相关资源
      最近更新 更多