在尝试让Alamofire上传图片时,我被困了三天.这个想法是Alamofire会将它发送到一个带有一些PHP代码的服务器.经过大量的尝试和寻找不同的地方,一些代码应该工作,但Alamofire的服务器端文档是可怕的.
最近对swift 3的更新没有多少答案明智......
这是我的Swift 3代码:
let imageData = UIImageJPEGRepresentation(imageFile!, 1)!
Alamofire.upload(
multipartFormData: { multipartFormData in
multipartFormData.append(imageData, withName: "image", fileName: "image.jpeg", mimeType: "file/jpeg")
},
to: "https://someadress.com/post/upload.php",
encodingCompletion: { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
upload.responseJSON { response in
debugPrint(response)
}
case .failure(let encodingError):
print(encodingError)
}
}
)
Run Code Online (Sandbox Code Playgroud)
这应该将图像上传到服务器,但我不知道如何正确获取保存在服务器上的图像.服务器实际上并不需要该文件的任何信息,因为它将为它生成一个新名称.然后它应该将该名称发送回应用程序.
我知道如何在Swift 3和php中处理JSON,因为我之前已经这样做了.我也确定至少有一些内容被上传到服务器,因为我已经获得了一些基本信息.
下面的PHP代码几乎肯定不好,但它主要是一个测试.
<?php
// get the file data
$fileData = file_get_contents('php://input');
// sanitize filename
$fileName = preg_replace("([^\w\s\d\-_~,;:\[\]\(\).])", '', $fileData);
// save to disk
$fileLocation = "../images/" . $fileName; …Run Code Online (Sandbox Code Playgroud)