I'm using this code (Swift) to upload an image that user selected from their photos to a server:
let imageFormatted = UIImageJPEGRepresentation(imageView.image!, 0.5);
let uuid = NSUUID().UUIDString
print ("MARK -- UUID is " + uuid)
Alamofire.upload(
.POST,
"http://www.memer.onlie/upload.php",
multipartFormData: { multipartFormData in
multipartFormData.appendBodyPart(data: imageFormatted!, name: "imagefile",
fileName: uuid + ".jpg", mimeType: "image/jpeg")
},
encodingCompletion: { encodingResult in
switch encodingResult {
case .Success(let upload, _, _):
upload.validate()
upload.responseJSON { response in
dispatch_async(dispatch_get_main_queue()) {
self.displayAlert("Uploaded!", message: "Your meme was uploaded, and you might see it in the app soon!", responseButtonText: "<3")
}
var json = JSON(data: response.data!)
print ("MARK -- JSON response: " + json["response"].stringValue)
}
print ("MARK -- Upload success!")
case .Failure(let encodingError):
print(encodingError)
print ("MARK -- Upload failure!")
self.displayAlert("Issue uploading.", message: "There was an issue uploading your meme.", responseButtonText: "Aww :(")
}
}
)
No image is being uploaded to the server. What can I correct to get this to work?
Edited code.
This thread helps you understand what you have not considered and what you need to do to solve the issue. I guess you need to set request header and body part properly. If you use Alamofire and have to use 'multipart/form-data' encoding type, you can write code like this.
Alamofire.upload(.POST, destURL, headers: yourHeader, multipartFormData: { multipartFormData in
if let imageData = UIImageJPEGRepresentation(image, 0.5) {
multipartFormData.appendBodyPart(data: imageData, name:"file", fileName: "imagefile", mimeType: "image/jpg")
}
// Append parameters you should send
for (key, value) in parameters {
multipartFormData.appendBodyPart(data: value.dataUsingEncoding(NSUTF8StringEncoding)!, name: key)
}
}, encodingCompletion: { encodingResult in
switch encodingResult {
case .Success(let upload, _, _):
upload.validate()
upload.responseJSON { response in
// do something if response is success
}
case .Failure(_):
// do something if response is fail
}
})
Related
I am new to swift and tried many blog posts and github to take image from library and upload it to server(php server side). can you please write the code which takes photo from photo library and upload it to server using alamofire and any other method.
below is the code i was trying to upload photo from photolibrary
#IBAction func upload(_ sender: Any) {
let picker = UIImagePickerController()
picker.delegate = self
picker.sourceType = UIImagePickerControllerSourceType.photoLibrary
picker.allowsEditing = false
self.present(picker, animated: true) {
}
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
if let originalImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
imageView.image = originalImage
let image = UIImage.init(named: "\(originalImage)")
let imgData = UIImageJPEGRepresentation(image!, 0.2)!
let parameters = ["user":"Sol", "password":"secret1234"]
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:"website")
{ (result) in
switch result {
case .success(let upload, _, _):
upload.uploadProgress(closure: { (progress) in
print("Upload Progress: \(progress.fractionCompleted)")
})
upload.responseJSON { response in
print(response.result.value)
}
case .failure(let encodingError):
print(encodingError)
}
}
}
self.dismiss(animated: true, completion: nil)
}
}
#IBAction func upload(_ sender: Any) {
let picker = UIImagePickerController()
picker.delegate = self
picker.sourceType = UIImagePickerControllerSourceType.photoLibrary
picker.allowsEditing = false
self.present(picker, animated: true) {
}
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
if let originalImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
imageView.image = originalImage
if let imgData = UIImageJPEGRepresentation(originalImage, 0.2) {
let parameters = ["user":"Sol", "password":"secret1234"]
upload(params: parameters, imageData: imgData)
}
}
picker.dismiss(animated: true, completion: nil)
}
func upload(params : [String: Any], imageData: Data) {
if let url = URL(string: "EnterUrl") {
Alamofire.upload(
multipartFormData: { (multipartdata) in
multipartdata.append(
imageData,
withName: "fileset",
fileName: String("\(Date().timeIntervalSince1970).jpg"),
mimeType: "image/jpg"
)
for (key,value) in params {
if let data = value as? String,
let data1 = data.data(using: .utf8)
{
multipartdata.append(
data1,
withName: key
)
}
}
},
to: url,
method: .post,
headers: nil,
encodingCompletion: { (result) in
switch result {
case .success(let upload, _, _):
upload.responseJSON(completionHandler: { (response) in
if let err = response.error {
print(err.localizedDescription)
} else {
print(response.result.value ?? "No data")
}
})
case .failure(let error):
print(error.localizedDescription)
}
}
)
}
}
}
try this.
I've looked up other solutions to this question but I don't fully understand what they're doing, and I can't get mine to work.
Here's my swift code
let imageData = UIImageJPEGRepresentation(image, 1.0)
if(imageData == nil ) { return }
let request = NSMutableURLRequest(URL: NSURL(string: ip)!) //ip is a string variable holding my correct ip address
request.HTTPMethod = "POST"
request.setValue("Keep-Alive", forHTTPHeaderField: "Connection")
let postString = "id=\(id)&"
let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
let session = NSURLSession(configuration: configuration, delegate: self, delegateQueue: NSOperationQueue.mainQueue())
let body = NSMutableData()
body.appendData(postString.dataUsingEncoding(NSUTF8StringEncoding)!)
body.appendData(imageData!)
request.HTTPBody = body
let task = session.uploadTaskWithRequest(request, fromData: imageData!)
task.resume()
And here's my PHP file
<?php
if (move_uploaded_file($_FILES['file']['tmp_name'], "image.jpg")) {
echo "File uploaded: ".$_FILES["file"]["name"];
}
else {
echo "File not uploaded";
}
?>
I have valid read and write access to the "image.jpg" file which sits on the front of my server, but it will still say that it could not upload the file. Any thoughts?
You're submitting the image as part of the POST request body. It won't be accessible using $_FILES.
You can Base-64 encode the image data, send the post string "id=\(id)&image=\(base64EncodedImageData)", then retrieve and decode it using $_POST.
You may want to consider using a networking library like Alamofire.
The manual and not recommended way: Change your PHP code to generate JSON responses.
echo json_encode(array("success" => true,
"filename" => basename($_FILES['image']['name']));
But as was mentioned you should let Alamofire do that for you. You can use MSProgress for a visual progress update in Alamofire.
let apiToken = "ABCDE"
Alamofire.upload(
.POST,
"http://sample.com/api/upload",
multipartFormData: { multipartFormData in
multipartFormData.appendBodyPart(data: imageData, name: "yourParamName", fileName: "imageFileName.jpg", mimeType: "image/jpeg")
multipartFormData.appendBodyPart(data: apiToken.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!, name :"api_token")
multipartFormData.appendBodyPart(data: otherBodyParamValue.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!, name :"otherBodyParamName")
},
encodingCompletion: { encodingResult in
switch encodingResult {
case .Success(let upload, _, _):
upload.progress { (bytesWritten, totalBytesWritten, totalBytesExpectedToWrite) in
print("Uploading Avatar \(totalBytesWritten) / \(totalBytesExpectedToWrite)")
dispatch_async(dispatch_get_main_queue(),{
/**
* Update UI Thread about the progress
*/
})
}
upload.responseJSON { (JSON) in
dispatch_async(dispatch_get_main_queue(),{
//Show Alert in UI
print("Avatar uploaded");
})
}
case .Failure(let encodingError):
//Show Alert in UI
print("Avatar uploaded");
}
}
);
Working on a Swift project, and apparently the file I'm uploading isn't an image. I'm also using the Alamofire utility.
let uuid = NSUUID().UUIDString
print ("MARK -- UUID is " + uuid)
let image = imageView.image
Alamofire.upload(.POST, "{RETRACTED}", multipartFormData: {
multipartFormData in
if let imageData = UIImageJPEGRepresentation(image!, 0.6) {
multipartFormData.appendBodyPart(data: imageData, name: uuid, fileName: uuid + ".png", mimeType: "image/png")
}
}, encodingCompletion: {
encodingResult in
switch encodingResult {
case .Success(let upload, _, _):
upload.responseJSON { response in
print(response.request) // original URL request
print(response.response) // URL response
print(response.data) // server data
print(response.result) // result of response serialization
if let JSON = response.result.value {
print ("JSON \(JSON)")
self.displayAlert("Uploaded!", message: "{RETRACTED}", responseButtonText: "{RETRACTED}")
}
}
case .Failure(let encodingError):
print(encodingError)
}
})
Here's the JSON response (I also have the PHP server side code if needed):
JSON {
response = "That file wasn't an image (Only .png and .jpg/.jpeg images are accepted). The type is ";
responseCode = 0;
}
Thanks guys.
You are sending an jpg image, but specifying mime type for png. Change mime type to "image/jpeg" or send a png file.
I'm trying to upload UIImage to a server via a web api. I'm creating my web rest API with laravel 5.2.
Here is my function in Swift which should make a post request to my API with the UIImage and some parameters:
func uploadWithAlamofire(imageUpload: UIImage) {
let image = imageUpload
// define parameters
let parameters = [
"hometown": "abc",
"living": "abc"
]
// Begin upload
Alamofire.upload(.POST, "http://localhost:8888/buyIT/public/app/api/createPost",
// define your headers here
headers: ["Authorization": "auth_token"],
multipartFormData: { multipartFormData in
// import image to request
if let imageData = UIImageJPEGRepresentation(image, 1) {
multipartFormData.appendBodyPart(data: imageData, name: "file", fileName: "myImage.png", mimeType: "image/png")
}
// import parameters
for (key, value) in parameters {
multipartFormData.appendBodyPart(data: value.dataUsingEncoding(NSUTF8StringEncoding)!, name: key)
}
},
// you can customise Threshold if you wish. This is the alamofire's default value
encodingMemoryThreshold: Manager.MultipartFormDataEncodingMemoryThreshold,
encodingCompletion: { encodingResult in
switch encodingResult {
case .Success(let upload, _, _):
upload.responseJSON { response in
print(response)
}
case .Failure(let encodingError):
print(encodingError)
}
})
}
But I don't know how to get the image and then upload it to my server.
Here is what I tried in my web api:
public function createPost(Request $request)
{
$file = $request->input('file');
$input = $request->only('hometown');
//Create deals folder if not exist
if (!file_exists('Upload/images')) {
mkdir('Upload/images', 0777, true);
}
if(file_exists('Upload/images'))
{
// SET UPLOAD PATH
$destinationPath = 'Upload/images';
// GET THE FILE EXTENSION
if ($file != null) {
$extension = $file->getClientOriginalExtension();
// RENAME THE UPLOAD WITH RANDOM NUMBER
$fileName = rand(11111, 99999) . '.' . $extension;
// MOVE THE UPLOADED FILES TO THE DESTINATION DIRECTORY
$upload_success = $file->move($destinationPath, $fileName);
//$filePath = url('/').'/'.$destinationPath.'/'.$fileName;
if($upload_success)
{
return "success";
}
else {
return "failed !!!";
}
}
}
else
{
return "failed";
}
return $file;
}
Or , You can use AlamoFire
func createMultipart(image: UIImage, callback: Bool -> Void){
// use SwiftyJSON to convert a dictionary to JSON
var parameterJSON = JSON([
"id_user": "test"
])
// JSON stringify
let parameterString = parameterJSON.rawString(encoding: NSUTF8StringEncoding, options: nil)
let jsonParameterData = parameterString!.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)
// convert image to binary
let imageData = UIImageJPEGRepresentation(image, 0.7)
// upload is part of AlamoFire
upload(
.POST,
URLString: "http://httpbin.org/post",
multipartFormData: { multipartFormData in
// fileData: puts it in "files"
multipartFormData.appendBodyPart(fileData: jsonParameterData!, name: "goesIntoFile", fileName: "json.txt", mimeType: "application/json")
multipartFormData.appendBodyPart(fileData: imageData, name: "file", fileName: "iosFile.jpg", mimeType: "image/jpg")
// data: puts it in "form"
multipartFormData.appendBodyPart(data: jsonParameterData!, name: "goesIntoForm")
},
encodingCompletion: { encodingResult in
switch encodingResult {
case .Success(let upload, _, _):
upload.responseJSON { request, response, data, error in
let json = JSON(data!)
println("json:: \(json)")
callback(true)
}
case .Failure(let encodingError):
callback(false)
}
}
)
}
let fotoImage = UIImage(named: "foto")
createMultipart(fotoImage!, callback: { success in
if success { }
})
I have been doing some task about sending a String array using multipart-formdata in Alamofire to an Laravel host.
My code like :
//End coding data.
let stringsData = NSMutableData()
for string in arrayFriend {
if let stringData = string.email.dataUsingEncoding(NSUTF8StringEncoding) {
stringsData.appendData(stringData)
}
}
//Upload by form data.
Alamofire.upload(.POST, HTDefines.WEBSERVICE.CREATE_NEW_EVENT, multipartFormData: { (multipartFormData) -> Void in
//FRIENDS
multipartFormData.appendBodyPart(data: stringsData, name: HTDefines.KEY.FRIENDS)
}) { (result) -> Void in
switch (result) {
case .Success(let upload, _, _):
upload.progress { bytesRead, totalBytesRead, totalBytesExpectedToRead in
progress(totalBytesRead: totalBytesRead, totalBytesExpectedToRead: totalBytesExpectedToRead)
}
upload.responseJSON { response in
switch response.result {
case .Success(let JSON):
}
case .Failure(let error):
}
}
case .Failure:
break
}
}
}
But my server has respond :
array_unique() expects parameter 1 to be array
Anyone can help me? Thank you so much.