An example of uploading file from Swift / Alamofire to PHP
Thomas Mak wrote at 2019-04-27.
https://gist.github.com/makzan/0e848de36a6c09ac8fb43cf39801f696
upload.php:
<!DOCTYPE html>
<html>
<head>
<title>Upload your files</title>
</head>
<body>
<form enctype="multipart/form-data" action="upload.php" method="POST">
<p>Upload your file</p>
<input type="file" name="uploaded_file"></input><br />
<input type="submit" value="Upload"></input>
</form>
</body>
</html>
<?PHP
if(!empty($_FILES['uploaded_file']))
{
$path = "uploads/";
$path = $path . basename( $_FILES['uploaded_file']['name']);
if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $path)) {
echo "The file ". basename( $_FILES['uploaded_file']['name']).
" has been uploaded";
} else{
echo "There was an error uploading the file, please try again!";
}
}
?>
Swift:
//
// ViewController.swift
// Upload Image Example
//
import UIKit
import Alamofire
class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
@IBOutlet weak var imageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
let picker = UIImagePickerController()
picker.delegate = self
picker.sourceType = .photoLibrary
present(picker, animated: true, completion: nil)
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
dismiss(animated: true, completion: nil)
imageView.image = info[.originalImage] as? UIImage
let imageData = (imageView.image?.jpegData(compressionQuality: 0.8))!
// https://stackoverflow.com/a/40521003
Alamofire.upload(multipartFormData: { (multipartFormData) in
multipartFormData.append(imageData, withName: "uploaded_file", fileName: "test.jpg", mimeType: "image/jpg")
}, to: "https://mz-main-makzan.c9.io/php-upload-demo/upload.php") { (result) in
switch result {
case .success(let upload, _, _):
upload.uploadProgress(closure: { (progress) in
print("Upload Progress: \(progress.fractionCompleted)")
})
upload.responseJSON { response in
print("Success")
print(response.result.value)
}
case .failure(let encodingError):
print("Error")
print(encodingError)
}
}
}
}
Result:
Comments
no comments yet.