Specific php and swift code for image uploading to sftp - php

php script and xcode shows that here is
****** response data =
Notice: Undefined index: userId in /home/raimonds/script.php on line 36
{"Message":"First name field empty","Status":"Error","userId":null}
so here is the php code :
<?php
if(!empty($_POST["firstName"])){
$firstName = isset($_POST["firstName"]) ? $_POST["firstName"] : "";
$lastName = isset($_POST["lastName"]) ? $_POST["lastName"] : "";
$userId = isset($_POST["userId"]) ? $_POST["userId"] : "";
$target_dir = "uploads/";
if(!file_exists($target_dir))
{
mkdir($target_dir, 0777, true);
}
$target_dir = $target_dir . "/" . basename($_FILES["file"]["name"]);
if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_dir)) {
echo json_encode([
"Message" => "The file ". basename( $_FILES["file"]["name"]). " has been uploaded.",
"Status" => "OK",
"userId" => $_POST["userId"]
]);
} else {
echo json_encode([
"Message" => "Sorry, there was an error uploading your file.",
"Status" => "Error",
"userId" => $_POST["userId"]
]);
}
}else{
echo json_encode([
"Message" => "First name field empty",
"Status" => "Error",
"userId" => $_POST["userId"]
]);
}
?>
can you please help me? xcode part was:
//
// ViewController.swift
// ImageUploader
//
// Created by Raimonds on 14/05/15.
// Copyright (c) 2015 Raimonds. All rights reserved.
//
import UIKit
class ViewController: UIViewController, UIImagePickerControllerDelegate,
UINavigationControllerDelegate
{
#IBOutlet weak var myImageView: UIImageView!
#IBOutlet weak var myActivityIndicator: UIActivityIndicatorView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func uploadButtonTapped(sender: AnyObject) {
myImageUploadRequest()
}
#IBAction func selectPhotoButtonTapped(sender: AnyObject) {
var myPickerController = UIImagePickerController()
myPickerController.delegate = self;
myPickerController.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
self.presentViewController(myPickerController, animated: true, completion: nil)
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject])
{
myImageView.image = info[UIImagePickerControllerOriginalImage] as?
UIImage
self.dismissViewControllerAnimated(true, completion: nil)
}
func myImageUploadRequest()
{
let myUrl = NSURL(string: "http://raimonds.gtd.lv/script.php");
let request = NSMutableURLRequest(URL: myUrl!);
request.HTTPMethod = "POST";
let param = [
"firstName" : "firstName",
"lastName" : "lastName",
"userId" : "9"
]
let boundary = generateBoundaryString()
request.setValue("multipart/form-data: boundary=\(boundary)" , forHTTPHeaderField: "Content-Type")
let imageData = UIImageJPEGRepresentation(myImageView.image, 1)
if (imageData==nil) {return; }
request.HTTPBody = createBodyWithParameters(param, filePathKey: "file", imageDataKey: imageData, boundary: boundary)
myActivityIndicator.startAnimating();
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in
if error != nil {
println("error=\(error)")
return
}
println("******* response = \(response)")
let responseString = NSString(data: data, encoding: NSUTF8StringEncoding)
println("****** response data = \(responseString!)")
var err: NSError?
var json = NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers, error: &err)
as? NSDictionary
dispatch_async(dispatch_get_main_queue(),{
self.myActivityIndicator.stopAnimating()
self.myImageView.image = nil;
});
}
task.resume()
}
func createBodyWithParameters(parameters: [String: String]?, filePathKey: String?, imageDataKey: NSData, boundary: String) -> NSData {
var 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")
}
}
let filename = "user-profile.jpg"
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.appendData(imageDataKey)
body.appendString("\r\n")
body.appendString("--\(boundary)--\r\n")
return body
}
func generateBoundaryString() -> String {
return "Boundary--\(NSUUID().UUIDString)"
}
}
extension NSMutableData {
func appendString(string: String) {
let data = string.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)
appendData(data!)
}
}

You have some problem in your swift code, because you don't send POST data into php
Try to look how send swift POST request:
http://ios-blog.co.uk/tutorials/swift-how-to-send-a-post-request-to-a-php-script/
You need something like that:
var url: NSURL = NSURL(string: "http://raimonds.gtd.lv/script.php")!
var request:NSMutableURLRequest = NSMutableURLRequest(URL:url)
request.HTTPMethod = "POST"
var bodyData = "firstName=firstName&lastName=lastName&userId=9"
request.HTTPBody = bodyData.dataUsingEncoding(NSUTF8StringEncoding);
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue())
{
(response, data, error) in
println(response)
}

Related

How upload Image with Swift5 and PHP to Server?

I'm trying to upload image to a local server using swift5 and php , Xcode Version 12.5.1 , Can you help me debug the code, or give me an example ?
Image upload example with Swift and PHP
I downloaded this example and change but it doesn't work, only folders created work
The modifications in the code :
import UIKit
class ViewController: UIViewController, UIImagePickerControllerDelegate,UINavigationControllerDelegate {
#IBOutlet weak var myActivityIndicator: UIActivityIndicatorView!
#IBOutlet weak var myImageView: UIImageView!
#IBAction func uploadButtonTapped(_ sender: Any) {
myImageUploadRequest()
}
#IBAction func selectPhotoButtonTapped(_ sender: Any) {
let myPickerController = UIImagePickerController()
myPickerController.delegate = self;
myPickerController.sourceType = UIImagePickerController.SourceType.photoLibrary
self.present(myPickerController, animated: true, completion: nil)
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
myImageView.image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage
myImageView.backgroundColor = UIColor.clear
self.dismiss(animated: true, completion: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
}
func generateBoundaryString() -> String
{
return "Boundary-\(UUID().uuidString)"
}
func myImageUploadRequest()
{
let myUrl = NSURL(string: "http://localhost/~*******/PHP/App/scripts/imageUpload.php");
//let myUrl = NSURL(string: "http://www.boredwear.com/utils/postImage.php");
let request = NSMutableURLRequest(url:myUrl! as URL);
request.httpMethod = "POST";
let param = [
"firstName" : "Sergey",
"lastName" : "Kargopolov",
"userId" : "9"
]
let boundary = generateBoundaryString()
request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
let imageData = myImageView.image!.jpegData(compressionQuality: 1)
if(imageData==nil) {
return;
}
print("imageData =\(imageData as Any)")
//request.HTTPBody = createBodyWithParameters(param, filePathKey: "file", imageDataKey: imageData!, boundary: boundary)
request.httpBody = createBodyWithParameters(parameters: param, filePathKey: "file", imageDataKey: imageData! as NSData, boundary: boundary) as Data
myActivityIndicator.startAnimating();
let task = URLSession.shared.dataTask(with: request as URLRequest) {
data, response, error in
if error != nil {
print("error=\(String(describing: error))")
return
}
// You can print out response object
print("******* response = \(String(describing: response))")
// Print out reponse body
let responseString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
print("****** response data = \(responseString!)")
do {
let json = try JSONSerialization.jsonObject(with: data!, options: []) as? NSDictionary
print(json as Any)
DispatchQueue.main.async {
self.myActivityIndicator.stopAnimating()
self.myImageView.image = nil;
}
}catch
{
print(error)
}
}
task.resume()
}
func createBodyWithParameters(parameters: [String: String]?, filePathKey: String?, imageDataKey: NSData, boundary: String) -> NSData {
let body = NSMutableData();
if parameters != nil {
for (key, value) in parameters! {
body.appendString(string: "--\(boundary)\r\n")
body.appendString(string: "Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n")
body.appendString(string: "\(value)\r\n")
}
}
let filename = "user-profile.jpg"
let mimetype = "image/jpg"
body.appendString(string: "--\(boundary)\r\n")
body.appendString(string: "Content-Disposition: form-data; name=\"\(filePathKey!)\"; filename=\"\(filename)\"\r\n")
body.appendString(string: "Content-Type: \(mimetype)\r\n\r\n")
body.append(imageDataKey as Data)
body.appendString(string: "\r\n")
return body
}
}
extension NSMutableData {
func appendString(string: String) {
//let data = string.data(using: String.Encoding.utf8, allowLossyConversion: true)
let data = string.data(using: String.Encoding.utf8, allowLossyConversion: true)
append(data!)
}
}
error message:
imageData =Optional(2322803 bytes)
2022-12-12 04:50:44.756347+0300 ImageUploadExample[7201:311148] [] nw_protocol_get_quic_image_block_invoke dlopen libquic failed
******* response = Optional(<NSHTTPURLResponse: 0x6000031e55a0> { URL: http://localhost/~*******/PHP/App/scripts/imageUpload.php } { Status Code: 200, Headers {
Connection = (
"Keep-Alive"
);
"Content-Type" = (
"text/html; charset=UTF-8"
);
Date = (
"Mon, 12 Dec 2022 01:50:44 GMT"
);
"Keep-Alive" = (
"timeout=5, max=100"
);
Server = (
"Apache/2.4.48 (Unix) PHP/8.1.13"
);
"Transfer-Encoding" = (
Identity
);
"X-Powered-By" = (
"PHP/8.1.13"
);
} })
****** response data = {"Message":"Sorry, there was an error uploading your file.","Status":"Error","userId":"9"}
Optional({
Message = "Sorry, there was an error uploading your file.";
Status = Error;
userId = 9;
})

Swift, php - can't upload image

I'm trying to upload an image to my web server from an ios app using PHP. I have the following code that manages the upload:
func uploadImage()
{
// get userId from saved credentials
let userId = UserDefaults.standard.string(forKey: "userId")
let param = ["userId":userId]
let imageData = UIImageJPEGRepresentation(profPicIV.image!, 1)
if(imageData == nil ) { return }
self.imgUploadButton.isEnabled = false
let uploadScriptUrl = URL(string: "http://xxx.xxx.xxx.xxx/scripts/imageUpload.php")
let boundary = generateBoundaryString()
var request = NSMutableURLRequest(url: uploadScriptUrl!)
request.httpMethod = "POST"
request.httpBody = createBodyWithParameters(param as! [String : String], filePathKey: "file", imageDataKey: imageData!, boundary: boundary)
request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
if (profPicIV.image == nil)
{
return
}
if(imageData == nil)
{
return
}
let session = URLSession.shared
let task = session.dataTask(with: request as URLRequest, completionHandler: {
(
data, response, error) in
guard ((data) != nil), let _:URLResponse = response, error == nil else {
print("error")
return
}
if let dataString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
{
print(dataString)
}
})
task.resume()
}
along with the createBodyWithParameters:
func createBodyWithParameters(_ 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")
}
}
let filename = "menu-image.jpg"
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
}
}
//add appendString function
extension NSMutableData {
func appendString(_ string: String) {
let data = string.data(using: String.Encoding.utf8, allowLossyConversion: false)
append(data!)
}
}
My PHP page on my webserver looks like this:
<?php
$user_id = $_POST["userId"];
$target_dir = "../profPics/" . $user_id;
if(!file_exists($target_dir))
{
mkdir($target_dir, 0744, true);
}
$target_dir = $target_dir . "/" . basename($_FILES["file"]["name"]);
if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_dir)) {
echo json_encode([
"message" => "The file ". basename( $_FILES["file"]["name"]). " has been uploaded.",
"status" => "OK",
"userId" => $user_id
]);
} else {
echo json_encode([
"message" => "Sorry, there was an error uploading your picture.",
"status" => "Error",
"userId" => $user_id
]);
}
?>
but then I try to upload an image and it prints out an error in the console saying:
{"message":"Sorry, there was an error uploading your picture.","status":"Error","userId":"6"}
It is correctly grabbing the userId from my saved login info, and is successfully posting it to the PHP page because the PHP page is returning it in the error (userId = 6.) I can't see anything wrong in the apache error.log. Can anyone see where I'm going wrong? Thanks!

Image is not uploaded in PHP using Swift

I am trying to use Google Vision API and upload an image using their API to get analysis. I am using this php code:
<?php
include("./includes/common.php");
include_once("creds.php"); // Get $api_key
$cvurl = "https://vision.googleapis.com/v1/images:annotate?key=" . $api_key;
$type = "LABEL_DETECTION";
//echo "Item is: " . $item;
//Did they upload a file...
$item = $_GET[item];
if($_FILES['photo']['name'])
{
}else{
echo "you did not upload image".
}
It always show "you did not upload image". And here's my Swift function where I upload the image:
func UploadRequest(img: UIImage, item: String)
{
let url = NSURL(string: "http://myurlhere")
let request = NSMutableURLRequest(URL: url!)
request.HTTPMethod = "POST"
let boundary = generateBoundaryString()
//define the multipart request type
request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
let image_data = UIImagePNGRepresentation(img)
if(image_data == nil)
{
return
}
let body = NSMutableData()
let fname = "image.png"
let mimetype = "image/png"
//define the data post parameter
body.appendData("--\(boundary)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
body.appendData("Content-Disposition:form-data; name=\"test\"\r\n\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
body.appendData("hi\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
body.appendData("--\(boundary)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
body.appendData("Content-Disposition:form-data; name=\"file\"; filename=\"\(fname)\"\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
body.appendData("Content-Type: \(mimetype)\r\n\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
body.appendData(image_data!)
body.appendData("\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
body.appendData("--\(boundary)--\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
request.HTTPBody = body
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(request) {
(
let data, let response, let error) in
guard let _:NSData = data, let _:NSURLResponse = response where error == nil else {
//EZLoadingActivity.hide(success: false, animated: true)
print("error")
return
}
let dataString = NSString(data: data!, encoding: NSUTF8StringEncoding)
print(dataString)
//EZLoadingActivity.hide(success: true, animated: true)
self.dismissViewControllerAnimated(true, completion: nil)
}
task.resume()
}
When I do print_r($_FILES), I get:
Array
(
[file] => Array
(
[name] => image.png
[type] => image/png
[tmp_name] => /tmp/phplSB2dc
[error] => 0
[size] => 864781
)
)
Your form data is currently submitting:
body.appendData("Content-Disposition:form-data; name=\"file\";...
And according to your print_r($_FILES), you should be using file instead of photo:
$_FILES['file']['name']
Also, you should be checking to make sure the file uploaded correctly using:
if ( $_FILES['file']['error'] == UPLOAD_ERR_OK )
{
//File uploaded correctly
}
func uploadMultipleIMAGE( APIStriing:NSString, dataString:NSString) -> Void
{
//Here dataString is image binary data just append you your url and just pass the image it will handle.
print("wscall URL string \(APIStriing)")
print("Data string URL string \(dataString)")
let postData = dataString.dataUsingEncoding(NSASCIIStringEncoding, allowLossyConversion: true)!
let postLength = "\(UInt(postData.length))"
let request = NSMutableURLRequest()
request.URL = NSURL(string: APIStriing as String)!
request.HTTPMethod = "POST"
request.setValue(postLength, forHTTPHeaderField: "Content-Length")
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.HTTPBody = postData
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue(), completionHandler: {(response: NSURLResponse?,data: NSData?,error: NSError?) -> Void in
if error == nil {
print("success")
}
else {
let alert = UIAlertView(title: "Sorry For Inconvenience ", message: "Contact to Administration", delegate: self, cancelButtonTitle: "Ok")
alert.show()
}
})
}
Note:- when you convert image to binary data you need to handle special character. here you can handle special character. follow this step.
1.
let imgData = UIImagePNGRepresentation(image)
imgBase64String = imgData!.base64EncodedStringWithOptions(NSDataBase64EncodingOptions())
var newimagdat = NSString()
newimagdat = newimagdat.stringByAppendingString(self.percentEscapeString(imgBase64String) as String)
imgarray.addObject(newimagdat)
Create character handler class something like that.
class handlecharacter: NSCharacterSet {
func urlParameterValueCharacterSet() -> NSCharacterSet {
let characterser = NSMutableCharacterSet.alphanumericCharacterSet()
characterser.addCharactersInString("-._~")
return characterser
}
}
Now create function your class where you want to upload images
func percentEscapeString(imgstring:NSString) -> NSString
{
let handle = handlecharacter()
return imgstring.stringByAddingPercentEncodingWithAllowedCharacters(handle.urlParameterValueCharacterSet())!
}

How can I insert a photo into a MySQL database with PHP using Swift iOS

I'm trying to insert a photo into a database using a php file with swift but I could only add the photo to a file under htdocs 'uploads' but I can't add the path to database.
Can someone tell me how to add a photo with parameters to database with swift knowing that I have used this tutorial:
http://swiftdeveloperblog.com/image-upload-example/
Here is my code:
Swift
// UploadViewController.swift
import UIKit
class UploadViewController: UIViewController,UIImagePickerControllerDelegate,UINavigationControllerDelegate
{
#IBOutlet weak var myActivityIndicator: UIActivityIndicatorView!
#IBOutlet weak var myImageView: UIImageView!
#IBAction func uploadButtonTapped(sender: AnyObject) {
//my Image upload
myImageUploadRequest()
}
override func viewDidLoad() {
super.viewDidLoad()
let defaults = NSUserDefaults.standardUserDefaults();
print("fffffff" + defaults.stringForKey("abc")!)
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func selectPhotoButtonTapped(sender: AnyObject) {
var myPickerController = UIImagePickerController()
myPickerController.delegate = self;
myPickerController.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
self.presentViewController(myPickerController, animated: true, completion: nil)
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject])
{
myImageView.image = info[UIImagePickerControllerOriginalImage] as? UIImage
self.dismissViewControllerAnimated(true, completion: nil)
}
func myImageUploadRequest()
{
let myUrl = NSURL(string: "http://localhost:8888/Swift/my-http-post-example.php");
//let myUrl = NSURL(string: "http://www.boredwear.com/utils/postImage.php");
let request = NSMutableURLRequest(URL:myUrl!);
request.HTTPMethod = "POST";
let param = [
"firstName" : "Sergey",
"lastName" : "Kargopolov",
"userId" : "9"
]
let boundary = generateBoundaryString()
request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
let imageData = UIImageJPEGRepresentation(myImageView.image!, 1)
if(imageData==nil) { return; }
request.HTTPBody = createBodyWithParameters(param, filePathKey: "file", imageDataKey: imageData!, boundary: boundary)
myActivityIndicator.startAnimating();
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in
if error != nil {
print("error=\(error)")
return
}
// You can print out response object
print("******* response = \(response)")
// Print out reponse body
let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("****** response data = \(responseString!)")
var err: NSError?
do {
var json = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as? NSDictionary
dispatch_async(dispatch_get_main_queue(),{
self.myActivityIndicator.stopAnimating()
self.myImageView.image = nil;
});
}
catch let error as NSError {
print("An error occurred: \(error)")
}
}
task.resume()
}
func createBodyWithParameters(parameters: [String: String]?, filePathKey: String?, imageDataKey: NSData, boundary: String) -> NSData {
var 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")
}
}
// defaults.setValue(String("0"), forKey: "abc")
let defaults = NSUserDefaults.standardUserDefaults()
if ((defaults.stringForKey("abc")!) == ""){
defaults.setValue(String("0"), forKey: "abc")
}
let filename = (defaults.stringForKey("abc")!)+".jpg"
defaults.setValue(String(Int((defaults.stringForKey("abc")!))!+1), forKey: "abc")
// let defaults = NSUserDefaults.standardUserDefaults();
//let filename = "user-profile.jpg"
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.appendData(imageDataKey)
body.appendString("\r\n")
body.appendString("--\(boundary)--\r\n")
return body
}
func generateBoundaryString() -> String {
return "Boundary-\(NSUUID().UUIDString)"
}
}
extension NSMutableData {
func appendString(string: String) {
let data = string.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)
appendData(data!)
}
}
Here the PHP file in which I couldn't insert the photo in data
<?php
$firstName = $_POST["firstName"];
$lastName = $_POST["lastName"];
$userId = $_POST["userId"];
$target_dir = "uploads/";if(!file_exists($target_dir))
{
mkdir($target_dir, 0777, true);
}
$target_dir = $target_dir . "/" . basename($_FILES["file"]["name"]);
if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_dir))
{
echo json_encode([
"Message" => "The file ". basename( $_FILES["file"]["name"]). " has been uploaded.",
"Status" => "OK",
"userId" => $_REQUEST["userId"]
]);
} else {
echo json_encode([
"Message" => "Sorry, there was an error uploading your file.",
"Status" => "Error",
"userId" => $_REQUEST["userId"]
]);
}
?>

How to upload an image from my iOS app to a PHP server?

I don't know php and swift well so can you help me? I have a server: cs.hisarschool.k12.tr/ecs.php and this is the code:
<?php
$firstName = $_POST["firstName"];
$lastName = $_POST["lastName"];
$userId = $_POST["userId"];
$target_dir = "/var/www/html/uploads";
// $myfile = fopen($target_dir, "w");
if(!file_exists($target_dir))
{
echo "creating directory";
mkdir($target_dir, 0555, true);
}
//$target_file = $target_dir . "/" . basename($_FILES["file"]["name"]);
$target_file = $target_dir . "/sc.jpg";
if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_file)) {
echo json_encode([
"Message" => "The file " . basename($_FILES["file"]["name"]) . " has been uploaded.",
"Status" => "OK",
"userId" => $_REQUEST["userId"]
]);
} else {
echo json_encode([
"Message" => "Sorry, there was an error uploading your file(" . basename($_FILES["filename"][name]) . ").",
"Status" => "Error",
"userId" => $_REQUEST["userId"]
]);
}
?>
The swift code:
//
// ViewController.swift
// application
//
// Created by kerem on 13/05/15.
// Copyright (c) 2015 kerem. All rights reserved.
//
import UIKit
class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
#IBOutlet weak var myImageView: UIImageView!
#IBOutlet weak var myActivityIndicator: UIActivityIndicatorView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func uploadButtonTapped(sender : AnyObject) {
myImageUploadRequest()
}
#IBAction func selectPhotoButtonTapped(sender : AnyObject) {
var myPickerController = UIImagePickerController()
myPickerController.delegate = self
myPickerController.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
self.presentViewController(myPickerController,animated:true, completion : nil)
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]) {
myImageView.image = info[UIImagePickerControllerOriginalImage] as? UIImage
self.dismissViewControllerAnimated(true, completion: nil)
}
//buraya yaz
func myImageUploadRequest() {
println("1")
let myUrl = NSURL(string : "cs.hisarschool.k12.tr/esc.php")//buraya
let request = NSMutableURLRequest(URL:myUrl!);
request.HTTPMethod = "POST";
let param = [
"firstName" : "Kerem",
"lastName" : "Guventurk",
"userId" : "dreamkiller"
]
let boundary = generateBoundaryString()
request.setValue("multipart/form-data; boundary=\(boundary)",forHTTPHeaderField:"Content-Type")
let imageData = UIImageJPEGRepresentation(myImageView.image, 1)
if (imageData == nil) {
return;
}
request.HTTPBody = createBodyWithParameters(param, filePathKey: "file", imageDataKey: imageData, boundary : boundary)
myActivityIndicator.startAnimating();
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data,response,error in
if error != nil {
println("error=\(error)")
return
}
println("******** response = \(response)")
let responseString = NSString(data:data,encoding:NSUTF8StringEncoding)
println("******** response data = \(responseString!)")
var err: NSError?
var json = NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers, error: &err) as? NSDictionary
dispatch_async(dispatch_get_main_queue(),{
self.myActivityIndicator.stopAnimating()
self.myImageView.image = nil;
});
}
task.resume()
}
//isim burada
func createBodyWithParameters(parameters: [String: String]?, filePathKey: String?, imageDataKey: NSData, boundary: String) -> NSData {
println("2")
var 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")
}
}
let filename = "user-profile.jpg"
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.appendData(imageDataKey)
body.appendString("\r\n")
body.appendString("–\(boundary)–\r\n")
return body
}
func generateBoundaryString() -> String {
return "Boundary-\(NSUUID().UUIDString)"
}
}
extension NSMutableData {
func appendString(string: String) {
let data = string.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)
appendData(data!)
}
}
I have the upload button and select button. The problem is, I can't actually upload a picture to the website. I tried different ways of selecting an URL, i used the directory of the server but none works... But then again, I don't know PHP or swift very well, I wrote this project with the help of a tutorial.

Categories