简体   繁体   中英

Uploading an image from iOS/Swift to PHP server

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");
        }
    }
); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM