我正在使用swift创建图像和视频上传iOS应用程序。我正在使用Alamofire库进行网络请求。下面是用户选择图像时在swift中运行的代码
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
dismissViewControllerAnimated(true, completion: nil)
guard let image = info[UIImagePickerControllerOriginalImage] as? UIImage else {
print("Did not get required image")
return
}
guard let imageData = UIImageJPEGRepresentation(image, 0.8) else {
return
}
Alamofire.upload(.POST, "http://localhost:8101/upload_request", multipartFormData: {
multipartFormData in
multipartFormData.appendBodyPart(data: imageData, name: "image")
}, encodingCompletion: {
encodingResult in
switch encodingResult {
case .Success(let upload, _, _):
upload.responseJSON(completionHandler: {
response in
debugPrint(response)
})
case .Failure(let encodingError):
print(encodingError)
}
})
}
以下是在Hapijs中处理请求的方式
server.route({
method: 'POST',
path: '/upload_request',
config: {
payload: {
maxBytes: 10 * 1024 * 1024,
output: 'stream',
parse: true,
allow: 'multipart/form-data'
}
},
handler: (request, reply) => {
var data = request.payload;
if (data.image) {
var filePath = 'new_image.jpg';
// data.image has data but is not of Stream.Readable
} else {
console.log('No data file');
}
}
});
问题是我没有将request.payload.image作为后端的流获取,因此我无法创建writeStream并将其传递给该writeStream。我做错了什么,或者遗漏了什么?我该怎么做才能读取数据并将其作为图像文件写入文件系统?
这是我在request.payload.image
中获得的数据的开头����JFIFHH��LExifMM*�i&��� ��8Photoshop 3.08BIM8BIM%��ُ��� ���B~��@ICC_PROFILE0ADBEmntrRGB XYZ �3;acspAPPLnone���-ADBE
cprt�2desc0kwtpt�bkpt�rTRC�gTRC�bTRC�rXYZ�gXYZbXYZtextCopyright 2000 Adobe Systems IncorporateddescAdobe RGB (1998)XYZ �Q�XYZ curv3curv3curv3XYZ �O��XYZ 4��,�XYZ &1/���� �"��
答案 0 :(得分:0)
我找到了答案。只需要进行一些小改动。我没有在Hapi.js上获得所需格式的数据的原因是因为我没有从Alamofire正确发送它。
这是请求从Alamofire发送的方式
Alamofire.upload(
.POST,
"http://localhost:8101/upload_request",
multipartFormData: { multipartFormData in
multipartFormData.appendBodyPart(data: self.fileData, name: "image", fileName: "imageToUpload.jpg",
mimeType: "image/jpeg")
},
encodingCompletion: { encodingResult in
switch encodingResult {
case .Success(let upload, _, _):
upload.responseJSON(completionHandler: { response in
debugPrint(response)
})
case .Failure(let encodingError):
print(encodingError)
}
})
应该在后端处理它的方式。只需确保创建了您正在写入的目录。
server.route({
path: '/upload_request',
method: 'POST',
config: {
payload: {
maxBytes: 20 * 1024 * 1024,
output: 'stream',
parse: true,
allow: 'multipart/form-data'
}
},
handler: (request, reply) => {
var data = request.payload;
if (data.image) {
var name = data.image.hapi.filename;
var path = __dirname + "/uploads/" + name;
var file = fs.createWriteStream(path);
file.on('error', (err) => {
console.error(err);
});
file.on('open', (err) => {
data.image.pipe(file);
});
data.image.on('end', (err) => {
var ret = {
filename: data.image.hapi.filename,
headers: data.image.hapi.headers
}
reply(ret);
})
}
}
});