[ios] ios Upload Image and Text using HTTP POST

Thanks for reading.

I am new to iOS and I am trying to upload an Image and a text using multi-part form encoding in iOS.

The curl equivalent is something like this: curl -F "param1=value1" -F "[email protected]" "http://some.ip.address:5000/upload"

The curl command above returns the expected correct response in JSON.

Problem: I keep getting a HTTP 400 request which means I am doing something wrong while composing the HTTP POST Body.

What I Did: For some reference, I tried Flickr API iOS app "POST size too large!" and Objective C: How to upload image and text using HTTP POST?. But, I keep getting a HTTP 400.

I tried the ASIHttpRequest but had a different problem there (the callback never got called). But, I didn't investigate further on that since I've heard the developer has stopped supporting the library: http://allseeing-i.com/[request_release];

Could someone please help me out?

This question is related to ios file-upload curl http-post image-uploading

The answer is


Here's code from my app to post an image to our web server:

// Dictionary that holds post parameters. You can set your post parameters that your server accepts or programmed to accept.
NSMutableDictionary* _params = [[NSMutableDictionary alloc] init];
[_params setObject:[NSString stringWithString:@"1.0"] forKey:[NSString stringWithString:@"ver"]];
[_params setObject:[NSString stringWithString:@"en"] forKey:[NSString stringWithString:@"lan"]];
[_params setObject:[NSString stringWithFormat:@"%d", userId] forKey:[NSString stringWithString:@"userId"]];
[_params setObject:[NSString stringWithFormat:@"%@",title] forKey:[NSString stringWithString:@"title"]];

// the boundary string : a random string, that will not repeat in post data, to separate post data fields.
NSString *BoundaryConstant = [NSString stringWithString:@"----------V2ymHFg03ehbqgZCaKO6jy"];

// string constant for the post parameter 'file'. My server uses this name: `file`. Your's may differ 
NSString* FileParamConstant = [NSString stringWithString:@"file"];

// the server url to which the image (or the media) is uploaded. Use your server url here
NSURL* requestURL = [NSURL URLWithString:@""]; 

// create request
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];                                    
[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
[request setHTTPShouldHandleCookies:NO];
[request setTimeoutInterval:30];
[request setHTTPMethod:@"POST"];

// set Content-Type in HTTP header
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", BoundaryConstant];
[request setValue:contentType forHTTPHeaderField: @"Content-Type"];

// post body
NSMutableData *body = [NSMutableData data];

// add params (all params are strings)
for (NSString *param in _params) {
    [body appendData:[[NSString stringWithFormat:@"--%@\r\n", BoundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n", param] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithFormat:@"%@\r\n", [_params objectForKey:param]] dataUsingEncoding:NSUTF8StringEncoding]];
}

// add image data
NSData *imageData = UIImageJPEGRepresentation(imageToPost, 1.0);
if (imageData) {
    [body appendData:[[NSString stringWithFormat:@"--%@\r\n", BoundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"image.jpg\"\r\n", FileParamConstant] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithString:@"Content-Type: image/jpeg\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:imageData];
    [body appendData:[[NSString stringWithFormat:@"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
}

[body appendData:[[NSString stringWithFormat:@"--%@--\r\n", BoundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]];

// setting the body of the post to the reqeust
[request setHTTPBody:body];

// set the content-length
NSString *postLength = [NSString stringWithFormat:@"%lu",(unsigned long) [body length]];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];

// set URL
[request setURL:requestURL];

Upload image with form data using NSURLConnection class in Swift 2.2:

    func uploadImage(){
        let imageData = UIImagePNGRepresentation(UIImage(named: "dexter.jpg")!)

        if imageData != nil{
            let str = "https://staging.mywebsite.com/V2.9/uploadfile"
            let request = NSMutableURLRequest(URL: NSURL(string:str)!)
            request.HTTPMethod = "POST"

            let boundary = NSString(format: "---------------------------14737809831466499882746641449")

            let contentType = NSString(format: "multipart/form-data; boundary=%@",boundary)
            request.addValue(contentType as String, forHTTPHeaderField: "Content-Type")

            let body = NSMutableData()

            // append image data to body
            body.appendData(NSString(format: "\r\n--%@\r\n", boundary).dataUsingEncoding(NSUTF8StringEncoding)!)
            body.appendData(NSString(format:"Content-Disposition: form-data; name=\"file\"; filename=\"img.jpg\"\\r\n").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

            do {
                let returnData = try NSURLConnection.sendSynchronousRequest(request, returningResponse: nil)
                let returnString = NSString(data: returnData, encoding: NSUTF8StringEncoding)
                print("returnString = \(returnString!)")
            }
            catch let  error as NSError {
                print(error.description)
            }
        }
    }

Note: Always use sendAsynchronousRequest method instead of sendSynchronousRequest for uploading/downloading data to avoid blocking main thread. Here I used sendSynchronousRequest for testing purpose only.


I can show you an example of uploading a .txt file to a server with NSMutableURLRequest and NSURLSessionUploadTask with help of a php script.

-(void)uploadFileToServer : (NSString *) filePath
{
NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://YourURL.com/YourphpScript.php"]];
[request setHTTPMethod:@"POST"]; 
[request addValue:@"File Name" forHTTPHeaderField:@"FileName"];
NSURLSessionConfiguration *defaultConfigObject = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration:defaultConfigObject];

NSURLSessionUploadTask* uploadTask = [defaultSession uploadTaskWithRequest:request fromFile:[NSURL URLWithString:filePath] completionHandler:^(NSData *data, NSURLResponse *response, NSError *error)
                                      {
                                          NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response;
                                          if (error || [httpResponse statusCode]!=202)
                                          {

                                              //Error
                                          }
                                          else
                                          {
                                             //Success
                                          }
                                          [defaultSession invalidateAndCancel];
                                      }];
[uploadTask resume];
}

php Script

<?php 
$request_body = @file_get_contents('php://input');
foreach (getallheaders() as $name => $value) 
{
    if ($FileName=="FileName") 
    {
        $header=$value;
        break;
    }
}   
$uploadedDir = "directory/";
@mkdir($uploadedDir);
file_put_contents($uploadedDir."/".$FileName.".txt",
$request_body.PHP_EOL, FILE_APPEND);
header('X-PHP-Response-Code: 202', true, 202);  
?>       

Use AFNetworking; Put other parameters in the parameter dictionary and append the image data in form data.

//Upload Image Using AFNetworking

-(BOOL)uploadImageAFNetworkingWithURL:(NSString *)path andImage:(UIImage *)image andImageNameWithExtension:(NSString *)strImageName andParamDict:(NSDictionary *)dictParam andKeyForUploadingImage:(NSString *)keyUplaodImg{

    NSData *imageData = UIImageJPEGRepresentation(image, 0.5);
    NSString *strError = EMPTY_STRING;

    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
     manager.requestSerializer = [AFJSONRequestSerializer serializer];
    [manager POST:path parameters:dictParam constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {

        [formData appendPartWithFileData:imageData name:keyUplaodImg fileName:strImageName mimeType:@"image/jpeg"];

    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"success = %@", responseObject);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"error = %@", error);
        NSLog(@"Response = %@", operation);
        [strError stringByAppendingString:STR_ERR_MESSAGE];
    }];
    if(strError.length>0){
        return NO;
    }else{
        return YES;
    }
}

XJones' answer worked like charm.

But he didn't mentioned/declared variables _params, BoundaryConstant and requestURL. So, i thought of posting that part as an add-on to his post, so that it may help others in future.

// Dictionary that holds post parameters. You can set your post parameters that your server accepts or programmed to accept.
NSMutableDictionary* _params = [[NSMutableDictionary alloc] init];
[_params setObject:[NSString stringWithString:@"1.0"] forKey:[NSString stringWithString:@"ver"]];
[_params setObject:[NSString stringWithString:@"en"] forKey:[NSString stringWithString:@"lan"]];
[_params setObject:[NSString stringWithFormat:@"%d", userId] forKey:[NSString stringWithString:@"userId"]];
[_params setObject:[NSString stringWithFormat:@"%@",title] forKey:[NSString stringWithString:@"title"]];

// the boundary string : a random string, that will not repeat in post data, to separate post data fields.
NSString *BoundaryConstant = [NSString stringWithString:@"----------V2ymHFg03ehbqgZCaKO6jy"];

// string constant for the post parameter 'file'. My server uses this name: `file`. Your's may differ 
NSString* FileParamConstant = [NSString stringWithString:@"file"];

// the server url to which the image (or the media) is uploaded. Use your server url here
NSURL* requestURL = [NSURL URLWithString:@""]; 

As i mentioned earler, this is not an answer by itself, just an addon to XJones' post.


For http post image and username and password sending through post method

 NSString *str=[NSString stringWithFormat:@"%@registration.php",appdel.baseUrl];
 NSString *urlString = [NSString stringWithFormat:@"%@",str];

 NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
 [request setURL:[NSURL URLWithString:urlString]];
 [request setHTTPMethod:@"POST"];
 NSMutableData *body = [NSMutableData data];
 NSString *boundary = @"---------------------------14737809831466499882746641449";
 NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
 [request addValue:contentType forHTTPHeaderField: @"Content-Type"];

 [body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
 [body appendData:[@"Content-Disposition: form-data; name=\"file\"; filename=\"a.jpg\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
 [body appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
 [body appendData:[NSData dataWithData:imgData]];
 [body appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];

 //  parameter username

 [body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
 [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"username\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];

 [body appendData:[userName.text dataUsingEncoding:NSUTF8StringEncoding]];
 [body appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];


 //  parameter token
 [body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
 [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"email\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];

 [body appendData:[eMail.text dataUsingEncoding:NSUTF8StringEncoding]];
 [body appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];


 // parameter method
 [body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
 [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"pass\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];

 [body appendData:[passWord.text dataUsingEncoding:NSUTF8StringEncoding]];
 [body appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];


 //parameter method
 NSLog(@"%@",countryCode);
 [body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
 [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"country\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];

 [body appendData:[countryCode dataUsingEncoding:NSUTF8StringEncoding]];
 [body appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];

 // close form
 [body appendData:[[NSString stringWithFormat:@"--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];


 // setting the body of the post to the reqeust
 [request setHTTPBody:body];


 NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
 // NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
 NSDictionary *dict=[NSJSONSerialization JSONObjectWithData:returnData options:NSJSONReadingMutableLeaves error:nil];
 Nslog(@"%@",dict);
 //

here's the working swift code translated from the code provided by @xjones. Thanks alot for your help mate. Yours was the only way that worked for me. I used this method to send 1 image and a another parameter to a webservice made in asp.net


                    let params = NSMutableDictionary()

                    let boundaryConstant  = "----------V2y2HFg03eptjbaKO0j1"

                    let file1ParamConstant = "file1"
                    params.setObject(device_id!, forKey: "deviceID")

                    let requestUrl = NSURL(string: "\(siteurl):\(port)/FileUpload/Upload")

                    let request = NSMutableURLRequest()

                    request.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData
                    request.HTTPShouldHandleCookies=false
                    request.timeoutInterval = 30
                    request.HTTPMethod = "POST"

                    let contentType = "multipart/form-data; boundary=\(boundaryConstant)"

                    request.setValue(contentType, forHTTPHeaderField: "Content-Type")

                    let body = NSMutableData()

                    // parameters

                    for param in params {

                    body.appendData("--\(boundaryConstant)\r\n" .dataUsingEncoding(NSUTF8StringEncoding)! )
                    body.appendData("Content-Disposition: form-data; name=\"\(param)\"\r\n\r\n" .dataUsingEncoding(NSUTF8StringEncoding)!)
                    body.appendData("\(param.value)\r\n" .dataUsingEncoding(NSUTF8StringEncoding)!)

                    }
                    // images

                    // image begin
                    body.appendData("--\(boundaryConstant)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)

                    body.appendData("Content-Disposition: form-data; name=\"\(file1ParamConstant)\"; filename=\"image.jpg\"\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
                    body.appendData("Content-Type: image/jpeg\r\n\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)

                    body.appendData(passportImageData)
                    body.appendData("\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)

                    // image end



                    body.appendData("--\(boundaryConstant)--\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)

                    request.HTTPBody  = body
                    let postLength = "\(body.length)"
                    request.setValue(postLength, forHTTPHeaderField: "Content-Length")
                    request.URL = requestUrl

                    var serverResponse = NSString()

                    let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
                        data, response, error in

                        if error != nil
                        {
                            print("error=\(error)")
                            return
                        }


                        print("response = \(response)")


                        let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
                        print("responseString = \(responseString!)")
                        serverResponse = responseString!


                        }

                            task.resume()

Here is a Swift version. Note that if you do not want to send form data it is still important to send the empty form boundary. Flask in particular expects form data followed by file data and will not populate request.files without the first boundary.

  let composedData = NSMutableData()

  // Set content type header
  let BoundaryConstant = "--------------------------3d74a90a3bfb8696"
  let contentType = "multipart/form-data; boundary=\(BoundaryConstant)"
  request.setValue(contentType, forHTTPHeaderField: "Content-Type")

  // Empty form boundary
  composedData.appendData("--\(BoundaryConstant)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)

  // Build multipart form to send image
  composedData.appendData("--\(BoundaryConstant)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
  composedData.appendData("Content-Disposition: form-data; name=\"file\"; filename=\"image.jpg\"\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
  composedData.appendData("Content-Type: image/jpeg\r\n\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
  composedData.appendData(rawData!)
  composedData.appendData("\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
  composedData.appendData("--\(BoundaryConstant)--\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)

  request.HTTPBody = composedData

  // Get content length
  let length = "\(composedData.length)"
  request.setValue(length, forHTTPHeaderField: "Content-Length")

Here is my similar network kit library for uploading files as multipart form:

WebRequest *request = [[WebRequest alloc] initWithPath:@"...documents/create.json"];

// optional attributes
request.delegate = delegate;
request.notificationName = @"NotificationDocumentUploaded";
request.queue = myQueue;

NSMutableData *body = [NSMutableData data];
NSString *boundary = @"TeslaSchoolProjectFormBoundary";

[body appendPartName:@"document[name]" value:@"Test" boundary:boundary];
[body appendPartName:@"document[description]" value:@"This is a description" boundary:boundary];
[body appendPartName:@"document[category]" value:@"Drama" boundary:boundary];
...
[body appendPartName:@"commit" value:@"Save" boundary:boundary];
NSData *fileData = [[NSData alloc] initWithContentsOfURL:someFileURL];
[body appendPartFile:fileName name:@"document[file]" data:fileData mimeType:mimeType boundary:boundary];
[body appendData:[[NSString stringWithFormat:@"--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];

[request setHTTPBody:body];

NSString *bodyLength = [NSString stringWithFormat:@"%lu",(unsigned long)[body length]];
[request addValue:bodyLength forHTTPHeaderField:@"Content-Length"];
[request setValue:[NSString stringWithFormat:@"multipart/form-data; charset=utf-8; boundary=%@", boundary] forHTTPHeaderField:@"Content-Type"];


// optional values
[request addValue:@"gzip,deflate,sdch" forHTTPHeaderField:@"Accept-Encoding"];
[request addValue:@"max-age=0" forHTTPHeaderField:@"Cache-Control"];
[request addValue:@"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8" forHTTPHeaderField:@"Accept"];
[request addValue:@"en-US,en;q=0.8,hr;q=0.6,it;q=0.4,sk;q=0.2,sl;q=0.2,sr;q=0.2" forHTTPHeaderField:@"Accept-Language"];


[request setHTTPMethod:@"POST"];
[WebRequestProcessor process:request];

Use the delegate for notifying about uploading progress.

Use the notificationName for notifying when request has finished.

Use the queue for adding this request into your operation queue so it will be processed in right time.


use below code. it will work fine for me.

+(void) sendHttpRequestWithArrayContent:(NSMutableArray *) array 
ToUrl:(NSString *) strUrl withHttpMethod:(NSString *) strMethod 
withBlock:(dictionary)block
{
if (![Utility isConnectionAvailableWithAlert:TRUE])
{
    [Utility showAlertWithTitle:@"" andMessage:@"No internet connection available"];
}


NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init] ;

[request setURL:[NSURL URLWithString:strUrl]];
[request setTimeoutInterval:120.0];
[request setHTTPMethod:strMethod];

NSString *boundary = @"---------------------------14737809831466499882746641449";
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
[request addValue:contentType forHTTPHeaderField: @"Content-Type"];

NSMutableData *body=[[NSMutableData alloc]init];

for (NSMutableDictionary *dict in array)
{
    if ([[dict valueForKey:[[dict allKeys]objectAtIndex:0]] isKindOfClass:[NSString class]])
    {
        [body appendData:[self contentDataFormStringWithValue:[dict valueForKey:[[dict allKeys]objectAtIndex:0]] withKey:[[dict allKeys]objectAtIndex:0]]];
    }
    else if ([[dict valueForKey:[[dict allKeys]objectAtIndex:0]] isKindOfClass:[UIImage class]])
    {
        [body appendData:[self contentDataFormImage:[dict valueForKey:[[dict allKeys]objectAtIndex:0]] withKey:[[dict allKeys]objectAtIndex:0]]];
    }
    else if ([[dict valueForKey:[[dict allKeys]objectAtIndex:0]] isKindOfClass:[NSMutableDictionary class]])
    {
        [body appendData:[self contentDataFormStringWithValue:[dict valueForKey:[[dict allKeys]objectAtIndex:0]] withKey:[[dict allKeys]objectAtIndex:0]]];
    }
    else
    {
        NSMutableData *dataBody = [NSMutableData data];
        [dataBody appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
        [dataBody appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"ipodfile.jpg\"\r\n",@"image"] dataUsingEncoding:NSUTF8StringEncoding]];
        [dataBody appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];

        [dataBody appendData:[dict valueForKey:[[dict allKeys]objectAtIndex:0]]];

        [body appendData:dataBody];
    }
}

[body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];

[request setHTTPBody:body];

[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError)
 {
     if (!data) {
         NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
          [dict setObject:[NSString stringWithFormat:@"%@",SomethingWentWrong] forKey:@"error"];
         block(dict);
         return ;
     }
     NSError *error = nil;
    // NSString *str=[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
     NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];
     NSLog(@"%@",dict);
     if (!dict) {
         NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
         [dict setObject:ServerResponceError forKey:@"error"];
         block(dict);
         return ;
     }
     block(dict);

 }];

}
+(NSMutableData*) contentDataFormStringWithValue:(NSString*)strValue 
withKey:(NSString *) key
{
NSString *boundary = @"---------------------------14737809831466499882746641449";
NSMutableData *data=[[NSMutableData alloc]init];
[data appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[data appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n",key] dataUsingEncoding:NSUTF8StringEncoding]];
[data appendData:[[NSString stringWithFormat:@"%@",strValue] dataUsingEncoding:NSUTF8StringEncoding]];  // title
return data;
}

+(NSMutableData*) contentDataFormImage:(UIImage*)image withKey:
(NSString *) key
{
NSString *boundary = @"---------------------------14737809831466499882746641449";
NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"ipodfile.jpg\"\r\n",key] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
NSData *imageData=UIImageJPEGRepresentation(image, 0.40);
[body appendData:imageData];

return body;
}

Examples related to ios

Adding a UISegmentedControl to UITableView Crop image to specified size and picture location Undefined Symbols error when integrating Apptentive iOS SDK via Cocoapods Keep placeholder text in UITextField on input in IOS Accessing AppDelegate from framework? Autoresize View When SubViews are Added Warp \ bend effect on a UIView? Speech input for visually impaired users without the need to tap the screen make UITableViewCell selectable only while editing Xcode 12, building for iOS Simulator, but linking in object file built for iOS, for architecture arm64

Examples related to file-upload

bootstrap 4 file input doesn't show the file name How to post a file from a form with Axios File Upload In Angular? How to set the max size of upload file The request was rejected because no multipart boundary was found in springboot Send multipart/form-data files with angular using $http File upload from <input type="file"> How to upload files in asp.net core? REST API - file (ie images) processing - best practices Angular - POST uploaded file

Examples related to curl

What is the incentive for curl to release the library for free? curl: (35) error:1408F10B:SSL routines:ssl3_get_record:wrong version number Converting a POSTMAN request to Curl git clone error: RPC failed; curl 56 OpenSSL SSL_read: SSL_ERROR_SYSCALL, errno 10054 How to post raw body data with curl? Curl : connection refused How to use the curl command in PowerShell? Curl to return http status code along with the response How to install php-curl in Ubuntu 16.04 curl: (35) SSL connect error

Examples related to http-post

Passing headers with axios POST request How to post raw body data with curl? Send FormData with other field in AngularJS How do I POST a x-www-form-urlencoded request using Fetch? OkHttp Post Body as JSON What is the difference between PUT, POST and PATCH? HTTP Request in Swift with POST method Uploading file using POST request in Node.js Send POST request with JSON data using Volley AngularJS $http-post - convert binary to excel file and download

Examples related to image-uploading

How to store images in mysql database using php Multiple Image Upload PHP form with one input Uploading Images to Server android How to upload images into MySQL database using PHP code Check file size before upload ios Upload Image and Text using HTTP POST Send file via cURL from form POST in PHP What is the best place for storing uploaded images, SQL database or disk file system?