I want to upload multiple images to my website using AFNetworking in swift, but only the last image in the array uploaded .
swift script:
let url = "http://pathtomysite"
let afHTTP : AFHTTPRequestSerializer = AFHTTPRequestSerializer()
let request: NSMutableURLRequest = afHTTP.multipartFormRequestWithMethod("POST", URLString: url, parameters: nil, constructingBodyWithBlock: {(formData: AFMultipartFormData) in
var i = 0
for image in upImage {
let imageData : NSData = UIImageJPEGRepresentation(image as UIImage, 0.5)!
formData.appendPartWithFileData(imageData, name: "uploaded_file", fileName: "imagex\(i)x.png", mimeType: "image/png")
i++
}
}, error: nil)
let managerS : AFURLSessionManager = AFURLSessionManager.init(sessionConfiguration: NSURLSessionConfiguration.defaultSessionConfiguration())
let uploadTask = managerS.uploadTaskWithStreamedRequest(request, progress: nil) { (response, AnyObject, error) -> Void in
if (error != nil){
print("error")
}
}
uploadTask.resume()
php script:
<?php
$dt = date("Ymdhis");
$fileInfo = pathinfo($_FILES['uploaded_file']['name']);
$file_path = "uploads/";
$file_path = $file_path . basename($_FILES['uploaded_file']['name']);
if (move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $file_path)) {
rename($file_path, 'uploads/' . $dt . '.' . $fileInfo['extension']);
}
?>
try this:
let url = "YOUR_URL"
let afHTTP : AFHTTPRequestSerializer = AFHTTPRequestSerializer()
let request: NSMutableURLRequest = afHTTP.multipartFormRequestWithMethod("POST", URLString: url, parameters: nil, constructingBodyWithBlock: {(formData: AFMultipartFormData) in
for (index, image) in upImage.enumerate() {
let imageData = UIImageJPEGRepresentation(image as UIImage, 0.5)!
formData.appendPartWithFileData(imageData, name: "uploaded_file[]", fileName: "imagex\(index)x.png", mimeType: "image/png")
}
}, error: nil)
let managerS : AFURLSessionManager = AFURLSessionManager.init(sessionConfiguration: NSURLSessionConfiguration.defaultSessionConfiguration())
let uploadTask = managerS.uploadTaskWithStreamedRequest(request, progress: nil) { (response, AnyObject, error) -> Void in
if (error != nil){
print("error")
}
}
uploadTask.resume()
and change your script to the following:
foreach ($_FILES["uploaded_file"]["tmp_name"] as $index => $tmp_name) {
$filePath = "uploads/" . basename($_FILES["uploaded_file"]["name"][$index]);
if (move_uploaded_file($tmp_name, $filePath)) {
// rename like you want to
}
}
the important piece is adding brackets to the uploaded_file[] in your upload code. if you do not include the [] every image upload overrides the last one.
the other important piece is the foreach loop in your script that handles multiple uploaded images instead of just one.
Related
I am learning "posting images to server", but when I tried the multiple images uploading, it always failed with reporting(JSON error, from my Xcode alert on iOS devices), it seems error is in the PHP side? But I am new, so anyone can help me to find any solution.
Xcode:
httpBody function
func createBodyWithParameters(parameters: [String : Any]?,boundary: String) -> NSData {
let body = NSMutableData()
if parameters != nil {
for (key, value) in parameters! {
body.append("--\(boundary)\r\n".data(using: .utf8)!)
body.append("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n".data(using: .utf8)!)
body.append("\(value)\r\n".data(using: .utf8)!)
}
}
for image in images {
let filename = "\(NSUUID().uuidString).jpg"
let imageData = image.jpegData(compressionQuality: 1)
let lineOne = "--" + boundary + "\r\n"
body.append(lineOne.data(using: .utf8, allowLossyConversion: false)!)
let lineTwo = "Content-Disposition: form-data; name=\"files\"; filename=\"\(filename)\"\r\n"
body.append(lineTwo.data(using: .utf8, allowLossyConversion: false)!)
let lineThree = "Content-Type: image/jpg\r\n\r\n"
body.append(lineThree.data(using: .utf8, allowLossyConversion: false)!)
body.append(imageData!)
let lineFive = "\r\n"
body.append(lineFive.data(using: .utf8, allowLossyConversion: false)!)
}
let lineSix = "--" + boundary + "--\r\n"
body.append(lineSix.data(using: .utf8, allowLossyConversion: false)!)
return body
}
http request function
func createRequest(parameters: [String : Any] , url : URL) -> URLRequest {
var request = URLRequest(url: url)
request.httpMethod = "POST"
let boundary = "Boundary-\(NSUUID().uuidString)"
request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
request.httpBody = createBodyWithParameters(parameters: parameters, boundary: boundary) as Data
return request
}
multi images upload functions
func uploadPostWithMultipleImages() {
guard let id = currentUser?["id"], let text = postTextView.text else {
return
}
// declaring keys and values to be sent to the server
let parameters = ["user_id": id, "text": text, "files": images]
// declaring URL and request
let url = URL(string: "http://localhost/projectExample/uploadPostMultipleImages.php")!
let request = createRequest(parameters: parameters, url: url)
URLSession.shared.dataTask(with: request) { (data, response, error) in
DispatchQueue.main.async {
// if error
if error != nil {
Helper().showAlert(title: "Server Error", message: error!.localizedDescription, in: self)
return
}
// access data / json
do {
// safe mode of accessing received data from the server
guard let data = data else {
Helper().showAlert(title: "Data Error", message: error!.localizedDescription, in: self)
return
}
// converting data to JSON
let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? NSDictionary
// safe mode of accessing / casting JSON
guard let parsedJSON = json else {
return
}
// if post is uploaded successfully -> come back to HomeVC, else -> show error message
if parsedJSON["status"] as! String == "200" {
// post notification in order to update the posts of the user in other viewControllers
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "uploadPost"), object: nil)
// comeback
self.dismiss(animated: true, completion: nil)
} else {
Helper().showAlert(title: "Error", message: parsedJSON["message"] as! String, in: self)
return
}
// error while accessing data / json
} catch {
Helper().showAlert(title: "JSON Error", message: error.localizedDescription, in: self)
return
}
}
}.resume()
}
PHP upload code
// generating absolute path to the folder for every user with his unique id
$folder = '/Applications/XAMPP/xamppfiles/htdocs/projectExample/posts/' . $user_id;
// creating fodler if it doesn't exist
if (!file_exists($folder)) {
mkdir($folder, 0777, true);
} else {
$return['folder_message'] = 'Could not create a directory';
}
foreach($_FILES['files']['name'] as $key =>$value) {
$file = $_FILES['files']['name'][$key];
$file_tmp = $_FILES['files']['tmp_name'][$key];
// path to the file. Full path of the file
$path = $folder . '/' . basename($file);
if (move_uploaded_file($file_tmp, $path)) {
// creating URL link to the image uploaded
$pictures .= 'http://localhost/projectExample/posts/' . $user_id . '/' . $file. " ";
$return['pictures'] = $pictures;
}
}//foreach
// Insert details into database
$result = $access->insertPost($user_id, $text, $pictures);
I use your swift code and upload images successfully, so I am sure it's your PHP code that has some error. please make sure that you have return a json that is correctly-formatted like :
echo '{"code" : 200}'
I have an IOS app that uses PHP for my API. My file upload is working fine but the name of the file is not appending to the file. I've mirrored other pages in my app but it's still not working although others are working fine. I’m able to see the file on the server, but the name is notes-.jpg. It’s not appending the puuid to the name per the code. I've implemented MessageKit on the ViewController that isn't working (just in case it makes a difference). Here is my code below, I feel like I'm looking for a needle in a haystack. The code is a little sloppy (please don't judge).
func createBodyWithParams(_ parameters: [String: String]?, filePathKey: String?, imageDataKey: Data, boundary: String) -> Data {
let body = NSMutableData();
if parameters != nil {
for (key, value) in parameters! {
body.appendString("--\(boundary)\r\n")
body.appendString("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n")
body.appendString("\(value)\r\n")
}
}
// if file is not selected, it will not upload a file to server, because we did not declare a name file
var filename = ""
if imageSelected == true {
filename = "notes-\(puuid).jpg"
print("name of file", filename)
}
let mimetype = "image/jpg"
body.appendString("--\(boundary)\r\n")
body.appendString("Content-Disposition: form-data; name=\"\(filePathKey!)\"; filename=\"\(filename)\"\r\n")
body.appendString("Content-Type: \(mimetype)\r\n\r\n")
body.append(imageDataKey)
body.appendString("\r\n")
body.appendString("--\(boundary)--\r\n")
return body as Data
}
func uploadImage(_ image: UIImage, completion: #escaping (URL?) -> Void) {
print("im in upload")
let avame = user!["ava"]
let user_id = user!["id"] as! String
let me = user!["username"] as! String
let recipientfe = getmessages["recipient"]
let uuidfe = getmessages["uuid"] as! String
let recipient = getmessages["username"] as! String
let rid = String(describing: getmessages["sender_id"]!)
let puuid = UUID().uuidString
let text = ""
let url = URL(string: "https://localhost/messagepost.php")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
let parameters = ["sender_id": user_id, "uuid": uuidfe, "sender": me, "recipient_id": rid, "recipient": recipient, "puuid": puuid, "text": text]
let boundary = "Boundary-\(UUID().uuidString)"
request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
var data = Data()
if image != nil {
data = image.jpegData(compressionQuality: 0.5)!
}
request.httpBody = createBodyWithParams(parameters, filePathKey: "file", imageDataKey: data, boundary: boundary)
URLSession.shared.dataTask(with: request) { data, response, error in
DispatchQueue.main.async(execute: {
if error != nil {
Helper().showAlert(title: "Server Error", message: error!.localizedDescription, in: self)
print("Server Error")
return
}
do {
guard let data = data else {
Helper().showAlert(title: "Data Error", message: error!.localizedDescription, in: self)
print("Data Error")
return
}
let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? NSDictionary
guard let parsedJSON = json else {
return
}
if parsedJSON["status"] as! String == "200" {
let newurl = parsedJSON["path"]
self.isSendingPhoto = true
guard let url = newurl else {
return
}
var message = Message(messageuser: self.sender, image: image)
message.downloadURL = url as? URL
self.save(message)
self.messagesCollectionView.scrollToBottom()
} else {
if parsedJSON["message"] != nil {
let message = parsedJSON["message"] as! String
Helper().showAlert(title: "Error", message: message, in: self)
print("where am i", parsedJSON["message"] as Any)
}
}
} catch {
Helper().showAlert(title: "JSON Error", message: error.localizedDescription, in: self)
print("where am i 2")
}
})
}.resume()
}
PHP Upload File
<?php
if (!empty($_REQUEST["uuid"])) {
$id = htmlentities($_REQUEST["id"]);
$recipient = htmlentities($_REQUEST["recipient"]);
$recipient_id = htmlentities($_REQUEST["recipient_id"]);
$uuid = htmlentities($_REQUEST["uuid"]);
$puuid = htmlentities($_REQUEST["puuid"]);
$text = htmlentities($_REQUEST["text"]);
$sender = htmlentities($_REQUEST["sender"]);
$sender_id = htmlentities($_REQUEST["sender_id"]);
if (isset($_FILES['file']) && $_FILES['file']['size'] > 1) {
$folder = "/home/xxxxx/public_html/notes/" . $uuid;
// if no posts folder, create it
if (!file_exists($folder)) {
mkdir($folder, 0777, true);
}
$picture = $folder . "/" . basename($_FILES["file"]["name"]);
chmod($picture,0777);
if (move_uploaded_file($_FILES["file"]["tmp_name"], $picture)) {
$path = "http://localhost/notes/" . $uuid . "/notes-" . $puuid . ".jpg";
$returnArray["message"] = "Post has been made with picture";
$returnArray["path"] = $path;
$returnArray["status"] = "200";
} else {
$returnArray["message"] = "Post has been made without picture";
$path = "";
}
$result=$access->insertMessage($recipient, $recipient_id, $uuid, $sender,$sender_id, $text, $path);
// STEP 2.5 If posts are found, append them to $returnArray
if (!empty($result)) {
$returnArray["message"] = $result;
$result = $access->updatebadge($recipient_id);
}
else {
$returnArray["message"] = "Couldnt insert". $puuid ."";
}
// if data is not passed - show posts except id of the user
}
else {
$username = htmlentities($_REQUEST["username"]);
$uuid = htmlentities($_REQUEST["uuid"]);
$recipient_id = htmlentities($_REQUEST["recipient_id"]);
$message = $access->conversation($username, $uuid, $recipient_id);
if (!empty($message)) {
$returnArray["message"] = $message;
}
}
}
$access->disconnect();
echo json_encode($returnArray);
?>
I figured it out. The body and headers in Swift were incorrect and weren't sending the correct file name.
I changed the body to:
// web development and MIME Type of passing information to the web server
let boundary = "Boundary-\(NSUUID().uuidString)"
request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
// access / convert image to Data for sending to the server
var data = Data()
// if picture has been selected, compress the picture before sending to the server
if image != nil {
data = image.jpegData(compressionQuality: 0.5)!
}
// building the full body along with the string, text, file parameters
request.httpBody = Helper().body(with: parameters, filename: "notes-\(puuid).jpg", filePathKey: "file", imageDataKey: data, boundary: boundary) as Data
I want to upload multiple images to my server using Alamofire Lib, but it's uploading 1 image only.
I'm using an image picker that returns an array of UIImage which is Named
imagesdata
This is my code:
#IBAction func uploadimages(_ sender: Any) {
Alamofire.upload(
multipartFormData: { multipartFormData in
for img in self.imagesdata{
let imgdata = UIImageJPEGRepresentation(img, 1.0)
multipartFormData.append(imgdata!,withName: "image", fileName: "image.jpg", mimeType: "image/jpeg")
print("$$$$$$$$$$ : \(imgdata!)")
}
},
to: "http://localhost/maarathtest/MAPI/img_upload.php",
encodingCompletion: { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
upload.responseJSON { response in
debugPrint(response)
}
case .failure(let encodingError):
print(encodingError)
}
}
)
}
and my PHP:
<?php
$response = array();
if (empty($_FILES["image"])) {
$response['File'] = "NOFILE";;
} else {
$filename = uniqid() . ".jpg";
// If the server can move the temporary uploaded file to the server
if (move_uploaded_file($_FILES['image']['tmp_name'], "images/" . $filename)) {
$response['status'] = "Success";
$response['filepath'] = "https://serverName/MAPI/images/" . $filename;
} else {
$response['status'] = "Failure";
}
}
echo json_encode($response);
?>
And my console log:
$$$$$$$$$$ : 5849743 bytes
$$$$$$$$$$ : 3253337 bytes
[Request]: POST http://localhost/maarathtest/MAPI/img_upload.php
[Response]: <NSHTTPURLResponse: 0x600000620940> { URL: http://localhost/maarathtest/MAPI/img_upload.php } { status code: 200, headers {
Connection = "Keep-Alive";
"Content-Length" = 101;
"Content-Type" = "text/html";
Date = "Thu, 25 May 2017 10:08:08 GMT";
"Keep-Alive" = "timeout=5, max=100";
Server = "Apache/2.4.18 (Unix) OpenSSL/1.0.2h PHP/5.5.35 mod_perl/2.0.8-dev Perl/v5.16.3";
"X-Powered-By" = "PHP/5.5.35";
} }
[Data]: 101 bytes
[Result]: SUCCESS: {
filepath = "https://serverName/MAPI/images/5926ad083b770.jpg";
status = Success;
}
I have changed my code as below,
Alamofire.upload(
multipartFormData: { multipartFormData in
var count = 1
for img in self.imagesdata{
let imgdata = UIImageJPEGRepresentation(img, 1.0)
multipartFormData.append(imgdata!,withName: "image\(count)", fileName: "image\(count).jpg", mimeType: "image/jpeg")
count += 1
}
},...
<?php
$response = array();
if (empty($_FILES["image1"])) {
$response['File1'] = "NOFILE";
} else {
$filename = uniqid() . ".jpg";
// If the server can move the temporary uploaded file to the server
if (move_uploaded_file($_FILES['image1']['tmp_name'], "images/" . $filename)) {
$response['status1'] = "Success";
$response['filepath1'] = "https://serverName/MAPI/images/" . $filename;
} else {
$response['status1'] = "Failure";
}
}
if (empty($_FILES["image2"])) {
$response['File2'] = "NOFILE";
} else {
$filename = uniqid() . ".jpg";
// If the server can move the temporary uploaded file to the server
if (move_uploaded_file($_FILES['image2']['tmp_name'], "images/" . $filename)) {
$response['status2'] = "Success";
$response['filepath2'] = "https://serverName/MAPI/images/" . $filename;
} else {
$response['status2'] = "Failure";
}
}
echo json_encode($response);
?>
Now it's uploading the images, but I don't think this is the proper way to do it, since I don't know how many images users want to upload!
How can I do this properly?
I have solved the issue, the code below hope to help some 1
Swift :
#IBAction func uploadimages(_ sender: Any) {
Alamofire.upload(
multipartFormData: { multipartFormData in
var count = 1
for img in self.imagesdata{
let imgdata = UIImageJPEGRepresentation(img, 0.5)
// the name should be as array other wise want work
multipartFormData.append(imgdata!,withName: "image[]", fileName: "image\(count).jpg", mimeType: "image/jpeg")
count += 1
}
},
to: "http://localhost/maarathtest/MAPI/img_upload.php",
encodingCompletion: { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
upload.responseJSON { response in
debugPrint(response)
}
case .failure(let encodingError):
print(encodingError)
}
}
)
}
PHP code sample :
<?php
$response = array();
if (empty($_FILES["image"])) {
$response['File1'] = "NOFILE";
}else {
//$filename = uniqid() . ".jpg";
// loop through files array from IOS app
foreach ($_FILES["image"]["tmp_name"] as $index => $tmp_name) {
$filePath = "images/" . basename($_FILES["image"]["name"][$index]);
if (move_uploaded_file($tmp_name, $filePath)) {
// Images are stored in file path , do what ever is needed
$response['filepath'][$index] = $filePath;
}
$response['status'] = "Success";
}
}
echo json_encode($response);
?>
Use this below code to upload multiple images to your server. I've put this in a method that takes in NSMutableArray of UIImage objects and their corresponding names in another array. You could change NSMutableArray to Swift Array if you want. After successful upload, the completion handler will get called and would return a mapped object based on your response:Code:
public func executeMultipleImageUpload<T: Mappable>(type: T.Type, url: String, parameters: Dictionary<String, String>, images: NSMutableArray?, names: [String], view: UIView, completion: #escaping(_ result: DataResponse<T>?)-> Void) {
//Calling Alamofire Upload method here...
Alamofire.upload(multipartFormData: { multipartFormData in // This is first param, the part data itself
if images == nil || images?.count == 0 {
print("There are no images to upload..!!")
} else {
//Append image data from array of images to multipart form data
var count = 1
for image in images! {
if let imageData = UIImageJPEGRepresentation(image as! UIImage, 0.76) {
multipartFormData.append(imageData, withName: names[count - 1], fileName: names[count - 1], mimeType: "image/jpeg")
}
count += 1
}
}
//We are encoding the parameters to be sent here in the multipart as well..
for (key, value) in parameters {
multipartFormData.append((value.data(using: .utf8))!, withName: key)
}}, to: url, method: .post, headers: ["": ""], //This is second param (to:)
encodingCompletion: { encodingResult in // This is third param (encodingCompletion:)
switch encodingResult {
case .success(let upload, _, _):
upload.response { [weak self] response in
guard self != nil else {
return
}
debugPrint(response)
}.validate().responseObject{
(response: DataResponse<T>) in
completion(response)
}
case .failure(let encodingError):
print("error:\(encodingError)")
}
})
}
I'm having a huge issue trying to upload my images to php.
my script works fine but when I go to view the image online it shows a broken image and if I download it and try to open in photoshop it says the image is corrupt.
Swift file upload script
func percentEscapeString(string: String) -> String {
return CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
string,
nil,
":/?#!$&'()*+,;=",
CFStringBuiltInEncodings.UTF8.rawValue) as String;
}
func imagePost(params : NSMutableDictionary, image: UIImage, url: String, postCompleted: (succeeded: Bool, msg: AnyObject) -> ()){
let request = NSMutableURLRequest(URL: NSURL(string: url)!)
let session = NSURLSession.sharedSession()
request.HTTPMethod = "POST"
let imageData = UIImageJPEGRepresentation(image, 0.9)
var base64String = self.percentEscapeString(imageData!.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0))) // encode the image
print(base64String)
params["image"] = [ "content_type": "image/jpeg", "filename":"test.jpg", "file_data": base64String]
do{
request.HTTPBody = try NSJSONSerialization.dataWithJSONObject(params, options: NSJSONWritingOptions(rawValue: 0))
}catch{
print(error)
}
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
let task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
NSOperationQueue.mainQueue().addOperationWithBlock {
var err: NSError?
var json:NSDictionary?
do{
json = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableLeaves) as? NSDictionary
}catch{
print(error)
err = error as NSError
}
// Did the JSONObjectWithData constructor return an error? If so, log the error to the console
if(err != nil) {
print("Response: \(response)")
let strData = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("Body: \(strData!)")
print(err!.localizedDescription)
let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("Error could not parse JSON: '\(jsonStr)'")
postCompleted(succeeded: false, msg: "Error")
}else {
// The JSONObjectWithData constructor didn't return an error. But, we should still
// check and make sure that json has a value using optional binding.
if let parseJSON = json {
// Okay, the parsedJSON is here, let's get the value for 'success' out of it
if let success = parseJSON["success"] as? Bool {
//print("Success: \(success)")
postCompleted(succeeded: success, msg: parseJSON["message"]!)
}
return
}
else {
// Woa, okay the json object was nil, something went worng. Maybe the server isn't running?
let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("Error could not parse JSON: \(jsonStr)")
postCompleted(succeeded: false, msg: "Unable to connect")
}
}
}
})
task.resume()
}
PHP script
$json = file_get_contents('php://input');
$obj = json_decode($json);
if($obj->image->content_type == "image/jpeg"){
$filename = $obj->id . time() . ".jpg";
$target_file = "userImages/$filename";
if(file_put_contents($target_file, $obj->image->file_data)){
$return_data = ["success"=>true, "message"=>"The photo has been uploaded."];
} else {
$return_data = ["success"=>false, "message"=>"Sorry, there was an error uploading your photo."];
}
}else{
$return_data = ["success"=>false,"message"=>"Not a JPEG image"];
}
part of the base64 before uploading.
%2F9j%2F4AAQSkZJRgABAQAASABIAAD%2F4QBYRXhpZgAATU0AKgAAAAgAAgESAAMAAAABAAEAAIdpAAQAAAABAAAAJgAAAAAAA6ABAAMAAAABAAEAAKACAAQAAAABAAAAlqADAAQAAAABAAAAyAAAAAD%2F7QA4UGhvdG9zaG9wIDMuMAA4QklNBAQAAAAAAAA4QklNBCUAAAAAABDUHYzZjwCyBOmACZjs%2BEJ%2B%2F8AAEQgAyACWAwEiAAIRAQMRAf
part of the base64 after uploading.
%2F9j%2F4AAQSkZJRgABAQAASABIAAD%2F4QBYRXhpZgAATU0AKgAAAAgAAgESAAMAAAABAAEAAIdpAAQAAAABAAAAJgAAAAAAA6ABAAMAAAABAAEAAKACAAQAAAABAAAAlqADAAQAAAABAAAAyAAAAAD%2F7QA4UGhvdG9zaG9wIDMuMAA4QklNBAQAAAAAAAA4QklNBCUAAAAAABDUHYzZjwCyBOmACZjs%2BEJ%2B%2F8AAEQgAyACWAwEiAAIRAQMRAf
Can anyone see any problems?
It seems that this code for replacing unwanted characters in the base64 doesn't work for php.
func percentEscapeString(string: String) -> String {
return CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
string,
nil,
":/?#!$&'()*+,;=",
CFStringBuiltInEncodings.UTF8.rawValue) as String;
}
I took it out and altered my php code to replace the unwanted characters.
if($obj->image->content_type == "image/jpeg"){
$filename = $obj->id . time() . ".jpg";
$target_file = "userImages/$filename";
$data = str_replace(' ', '+', $obj->image->file_data);
$data = base64_decode($data);
if(file_put_contents($target_file, $data)){
$return_data = ["success"=>true, "message"=>"The photo has been uploaded."];
} else {
$return_data = ["success"=>false, "message"=>"Sorry, there was an error uploading your photo."];
}
}else{
$return_data = ["success"=>false,"message"=>"Not a JPEG image"];
}
This fixed it for me.
|*| Swift2 Code : To Convert Image to String for sending to Php Server
let NamImjVar = UIImage(named: "NamImjFyl")
let ImjDtaVar = UIImageJPEGRepresentation(NamImjVar!, 1)
let ImjSrgVar = ImjDtaVar!.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue:0))
|*| Php Code : To Convert String data back to image and save in server
<?php
$NamImjSrgVar = $_REQUEST["ImjKey"];
header('Content-Type: image/jpeg');
$NamImjDtaVar = str_replace(' ', '+', $NamImjSrgVar);
$NamImjHexVar = base64_decode($NamImjDtaVar);
file_put_contents("NamFyl.jpg", $NamImjHexVar)
?>
i have a problem with my php file.
I'm trying to upload an image through xcode to mysql db.
here's swift code
let image = UIImage(named: "image.jpg")
var imageData = UIImageJPEGRepresentation(image, 1)
if imageData != nil{
var request = NSMutableURLRequest(URL: NSURL(string:"link php file")!)
var session = NSURLSession.sharedSession()
request.HTTPMethod = "POST"
var boundary = NSString(format: "---------------------------14737809831466499882746641449")
var contentType = NSString(format: "multipart/form-data; boundary=%#",boundary)
request.addValue(contentType, forHTTPHeaderField: "Content-Type")
var body = NSMutableData.alloc()
// Image
body.appendData(NSString(format: "--%#\r\n", boundary).dataUsingEncoding(NSUTF8StringEncoding)!)
body.appendData(NSString(format:"Content-Disposition: attachment; name=\"userfile\"; filename=\"img.jpg\"").dataUsingEncoding(NSUTF8StringEncoding)!)
//body.appendData(NSString(format: "Content-Type: application/octet-stream\r\n\r\n").dataUsingEncoding(NSUTF8StringEncoding)!)
body.appendData(imageData)
body.appendData(NSString(format: "\r\n--%#--\r\n", boundary).dataUsingEncoding(NSUTF8StringEncoding)!)
request.HTTPBody = body
var returnData = NSURLConnection.sendSynchronousRequest(request, returningResponse: nil, error: nil)
var returnString = NSString(data: returnData!, encoding: NSUTF8StringEncoding)
println("returnString \(returnString)")
}
and here's php code:
$myparam = $_FILES['userfile']; //getting image Here //getting textLabe Here
$target_path = "uploads/".basename($myparam['filename']);
if(move_uploaded_file($myparam['tmp_name'], $target_path)){
$var = 1;
}
else {
$var = 0;
}
$myarray = array("response" => $var, "path" => $target_path);
$out = json_encode($myarray);
echo($out);
the problem is in the path. it returns wrong path and so i found no image in "uploads" folder. if i change target_path in php file (for example $target_path = "uploads/image.jpg"), image is saved.
i think it's a very easy problem but i don't understand what i have to change.
thanks for any help
hi