My Swift 3客户端代码:
Alamofire.upload(multipartFormData: { (multipartFormData) in
let path = "\(Bundle.main.resourcePath!)/images"
let all = try? FileManager.default.contentsOfDirectory(at: URL(string: path)!, includingPropertiesForKeys: nil, options: [])
let filtered = all!.filter { $0.pathExtension == "jpg" }
for item in filtered {
let url = URL(fileURLWithPath: item.path, isDirectory: false)
multipartFormData.append(url, withName: item.path)
}
}, to: "http://localhost:3000/upload") {
(encodingResult) in
switch encodingResult {
case .success(let upload, _, _):
upload.responseJSON { response in
debugPrint(response)
}
case .failure(let encodingError):
print(encodingError)
}
}
我的服务器代码:
app.post('/upload', (req,res) => {
console.log(req.files)
res.send('{"status":"ok"}')
})
但是req.files是未定义的。我想知道原因是什么。如何实现NodeJ?
编辑于26/6/2017(已解决!):
按照Svenskunganka的建议,我在我的NodeJs代码中添加了multer:
const multer = require('multer')
const upload = multer({ dest: 'uploads/' })
app.post('/photos/upload', upload.array('photos', 12), (req, res) => {
console.log(req.files)
res.send('{"status":"ok"}')
})
我的快捷代码:
Alamofire.upload(multipartFormData: { (multipartFormData) in
let path = "\(Bundle.main.resourcePath!)/images"
let all = try? FileManager.default.contentsOfDirectory(at: URL(string: path)!, includingPropertiesForKeys: nil, options: [])
let filtered = all!.filter { $0.pathExtension == "jpg" }
for item in filtered {
let url = URL(fileURLWithPath: item.path, isDirectory: false)
multipartFormData.append(url, withName: "photos", fileName: url.lastPathComponent, mimeType: "image/jpeg")
}
}, to: "http://localhost:3000/upload") {
(encodingResult) in
switch encodingResult {
case .success(let upload, _, _):
upload.responseJSON { response in
debugPrint(response)
}
case .failure(let encodingError):
print(encodingError)
}
}
然后它工作正常。需要记住的一点是,upload.array('photos', 12)
中的数字 12 是将上传的多部分的最大数量。如果数字大于12,那么将得到一个" Undefined"服务器出错。