使用 Alamofire 和 Multer 上传文件

Uploading files with Alamofire and Multer

我正在尝试使用 Alamofire 将图像数据从 iOS 上传到带有 Multer 的 Express 服务器。 req.file是未定义的,req.body的形式是{ file: <bytes> }。没有错误消息,但文件没有出现。这是我的代码:

var bodyParser = require('body-parser')
var multer = require('multer')

app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: false }))

app.post('/api/photos/upload', function(req, res) {
    var upload = multer({ dest: 'public/images/content/'}).single('file')
    upload(req, res, function(err) {
        if (err) {
            console.log("Error uploading file: " + err)
            return
        }

        // req.file = req.body
        console.log(req.body) // form fields
        console.log(req.file) // form file
    })

    res.json('yeah')
})

在 iOS:

let url = fullURL("api/photos/upload")

Alamofire.upload(.POST, url, multipartFormData: { multipartFormData in

        if let image = image {
            if let imageData = UIImageJPEGRepresentation(image, 0.5) {
                multipartFormData.appendBodyPart(data: imageData, name: "file")
            }
        }

        }, encodingCompletion: { encodingResult in

            switch encodingResult {
            case .Success(let upload, _, _):
                upload.responseJSON { response in

                    switch response.result {
                    case .Success:
                        print("success")
                    case .Failure(let error):
                        print(error)
                    }

                }
            case .Failure(let encodingError):
                print(encodingError)
            }

    })

这让我困惑了几个小时,非常感谢任何帮助!

更新 HTML 表单在 Express 端点上运行良好,所以这肯定是 Alamofire 发送的请求有问题。我已经尝试了一堆使用 Alamofire 上传的示例,但它们都发送了相同的错误请求。必须有一种方法可以发出与 HTML 表单相同的请求,但使用 Alamofire。

另一个更新
我现在只使用 busboy-connect,它运行良好,并且具有更大的灵活性。

您的问题可能是由于没有使用 multer 作为中间件造成的:

var upload = multer({ dest: 'public/images/content/'})

app.post('/api/photos/upload', upload.single('file'), function(req, res) {
  // req.file should be populated now
})

在 express 中,您可以根据需要添加任意数量的中间件:

app.post('/path',
  middleware1,
  middleware2,
  middleware3,
  ...,
  function(req, res) {
    // All middlewares has been executed
  })

我刚刚能够让它工作。事实证明,您必须使用 Alamofire 指定文件名和 mimeType,以便 multer 在服务器端获取上传。因此,您添加图像的代码应如下所示:

if let image = image {
    if let imageData = UIImageJPEGRepresentation(image, 0.5) {
        multipartFormData.appendBodyPart(data: imageData, name: "file", fileName: "fileName.jpg", mimeType: "image/jpeg")
    }
}

你知道,方法multipartFormData.append(value.data, withName: name, fileName: filename, mimeType: mimeType) 和multipartFormData.append(value.data , 名称: 键).

当你使用前者时,multer会把它当作req.file、后者当作req.body。