ios Upload Image and Text using HTTP POST

后端 未结 10 1979
执笔经年
执笔经年 2020-11-22 08:27

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

相关标签:
10条回答
  • 2020-11-22 09:08

    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.

    0 讨论(0)
  • 2020-11-22 09:09

    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];
    
    0 讨论(0)
  • 2020-11-22 09:10

    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.

    0 讨论(0)
  • 2020-11-22 09:11

    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);
     //
    
    0 讨论(0)
提交回复
热议问题