我正在尝试将图像从ImageView上传到远程服务器。
这是我的代码:
func subir_imagen(){
let image = self.foto.image
let imgData = image!.jpegData(compressionQuality: 1)!
let parameters = ["name": "jogua"] //Optional for extra parameter
Alamofire.upload(multipartFormData: { multipartFormData in
multipartFormData.append(imgData, withName: "fileset",fileName: "file.jpg", mimeType: "image/jpg")
for (key, value) in parameters {
multipartFormData.append(value.data(using: String.Encoding.utf8)!, withName: key)
} //Optional for extra parameters
},
to:"https://.../subir_foto_dispositivo.php")
{ (result) in
switch result {
case .success(let upload, _, _):
upload.uploadProgress(closure: { (progress) in
print("Upload Progress: \(progress.fractionCompleted)")
})
upload.responseJSON { response in
print(response)
}
case .failure(let encodingError):
print(encodingError)
}
}
}
这是文件subir_foto_dispositivo.php:
// Save the image file
move_uploaded_file($_FILES["image"]["tmp_name"], $_FILES["image"]["name"]);
// Send some dummy result back to the iOS app
$result = array();
$result["user"] = $user;
$result["message"] = "Success!";
$result["files"] = $_FILES;
$result["post"] = $_POST;
echo json_encode($result);
这是上传图像时调试器中的输出:
Upload Progress: 0.21640112366409928
Upload Progress: 0.4362101390394442
Upload Progress: 0.6628349378372804
Upload Progress: 0.8485650361001688
Upload Progress: 1.0
SUCCESS: {
files = {
fileset = {
error = 0;
name = "file.jpg";
size = 9615058;
"tmp_name" = "/tmp/phpH6Au4W";
type = "image/jpg";
};
};
message = "Success!";
post = {
name = jogua;
};
user = "<null>";
}
我没有收到任何警告或错误,但是图像没有上传到服务器,至少在文件夹中找不到它。
我想我缺少什么。
以下为我工作:
for item in imageParameter{
if item as? UIImage != nil { //check here image is null or not
let image = item as! UIImage
if let imgjpgData = image.jpegData(compressionQuality: 0.3){
imageData.append(imgjpgData)
}
}
}
Alamofire.upload(multipartFormData: { (multipartFormData) in
for (key, value) in params {
if let data = value.data(using: String.Encoding.utf8.rawValue) {
multipartFormData.append(data, withName: key)
}
}
for data in imageData {
multipartFormData.append(data, withName: "file", fileName: "image.jpg", mimeType: "image/jpeg")
}
}, usingThreshold: UInt64.init(), to: serverUrl, method: .post, headers: localHeaders) { (result) in
switch result{
case .success(let upload, _, _):
upload.responseJSON { response in
print("Succesfully uploaded")//other stuff}
这可能有帮助。
更新:
var tempImg: UIImage?
if let img = self.imgViewProfile.image{
tempImg = img
}
else{
//image is null
}