1

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;
    }
Loc Dai Le
  • 1,661
  • 4
  • 35
  • 70
  • please check out [Upload image with parameters in Swift](http://stackoverflow.com/questions/26162616/upload-image-with-parameters-in-swift) – Mr.Geeker Mar 03 '16 at 10:36

1 Answers1

0

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 { }
})
Mr.Geeker
  • 395
  • 3
  • 13