我想将jpeg图像(从UIImage转换)上传到运行node.js并使用multer进行文件存储的服务器。我尝试了邮递员的要求,并且在那儿工作正常。但是,当我在Swift中尝试相同的请求时,服务器会抛出此错误:
TypeError: Cannot read property 'path' of undefined
将图片保存到目录的代码:
// Upload image
router.post('/image/:id', upload.single('image'), (req, res) => {
var img = fs.readFileSync(req.file.path);
let uploadTime = new Date().toString()
let image = new Image({
imgID: req.params.id,
contentType: req.file.mimetype,
image: img,
created: uploadTime,
path: req.file.path
})
image.save()
.then(() => {
res.status(200).send("Uploaded photo")
})
.catch(err => {
res.status(500).json(err)
})
})
上传任务:
let url = URL(string: "myServerURL")!
var request = URLRequest(url: url)
let boundary = "Boundary-\(NSUUID().uuidString)"
request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
let imageData = image.jpegData(compressionQuality: 0.9)
request.httpBody = imageData
request.httpMethod = httpMethods.post
URLSession.shared.dataTask(with: request) { data, response, error in
if error == nil {
print("success")
}
}.resume()
这可能是通过在请求正文中添加路径参数来解决的,但是由于我对请求还很陌生,所以我不知道该怎么做。预先感谢