Skip to content

Instantly share code, notes, and snippets.

@makzan
Created April 9, 2019 05:13
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save makzan/0e848de36a6c09ac8fb43cf39801f696 to your computer and use it in GitHub Desktop.
Save makzan/0e848de36a6c09ac8fb43cf39801f696 to your computer and use it in GitHub Desktop.
Demo on uploading image to PHP from Alamofire
<!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!";
}
}
?>
//
// 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)
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment