Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7945265
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 4, 20262026-06-04T00:48:34+00:00 2026-06-04T00:48:34+00:00

Hi I am uploading image on php server and successfully uploaded with the help

  • 0

Hi I am uploading image on php server and successfully uploaded with the help of this code

- (NSString*)uploadData:(NSData *)data toURL:(NSString *)urlStr:(NSString *)_userID
{
    // File upload code adapted from http://www.cocoadev.com/index.pl?HTTPFileUpload
    // and http://www.cocoadev.com/index.pl?HTTPFileUploadSample
    NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
    [request setURL:[NSURL URLWithString:urlStr]];
    [request setHTTPMethod:@"POST"];

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


    NSMutableData *body = [NSMutableData data];
    [body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]];
//  [body appendData:[[NSString stringWithFormat:@"userId=%@",_userID] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"userfile\"; filename=\"image%@.jpg\"\r\n", _userID] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithString:@"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[NSData dataWithData:data]];
    [body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]];
    // setting the body of the post to the reqeust
    [request setHTTPBody:body];

    // now lets make the connection to the web
    NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];

    NSLog(@"%@",returnString);

    return returnString;

}

Now i want to send my user Id also on derver side how can i send my user id? I tried to it in this way

[body appendData:[[NSString stringWithFormat:@"userId=%@",_userID] dataUsingEncoding:NSUTF8StringEncoding]];

but in vain then i tried to send it in this way

[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"userfile\"; filename=\"image%@.jpg\"; userId=\"%@\"\r\n", _userID, _userID] dataUsingEncoding:NSUTF8StringEncoding]];

but again in vain so kindly guide me what to do!

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-04T00:48:35+00:00Added an answer on June 4, 2026 at 12:48 am

    If you haven’t thought about using AFNetworking, you should. It makes dealing with web-services much easier. I have done something similar to what I think you are wanting to do. I wrote a custom class to fire off network requests. Here ya go:
    NetworkClient.h

    /*
     NetworkClient.h
    
     Created by LJ Wilson on 2/3/12.
     Copyright (c) 2012 LJ Wilson. All rights reserved.
     License:
    
     Permission is hereby granted, free of charge, to any person obtaining a copy of this software 
     and associated documentation files (the "Software"), to deal in the Software without restriction, 
     including without limitation the rights to use, copy, modify, merge, publish, distribute, 
     sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is 
     furnished to do so, subject to the following conditions:
    
     The above copyright notice and this permission notice shall be included in all copies or 
     substantial portions of the Software.
    
     THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT 
     NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 
     NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, 
     DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT 
     OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
     */
    
    #import <Foundation/Foundation.h>
    
    extern NSString * const APIKey;
    
    @interface NetworkClient : NSObject
    
    +(void)processURLRequestWithURL:(NSString *)url 
                          andParams:(NSDictionary *)params 
                              block:(void (^)(id obj))block;
    
    +(void)processURLRequestWithURL:(NSString *)url 
                          andParams:(NSDictionary *)params 
                        syncRequest:(BOOL)syncRequest
                              block:(void (^)(id obj))block;
    
    +(void)processURLRequestWithURL:(NSString *)url 
                          andParams:(NSDictionary *)params 
                        syncRequest:(BOOL)syncRequest
                 alertUserOnFailure:(BOOL)alertUserOnFailure
                              block:(void (^)(id obj))block;
    
    +(void)processFileUploadRequestWithURL:(NSString *)url 
                                 andParams:(NSDictionary *)params 
                                  fileData:(NSData *)fileData 
                                  fileName:(NSString *)fileName
                                  mimeType:(NSString *)mimeType 
                                     block:(void (^)(id obj))block;
    
    +(void)handleNetworkErrorWithError:(NSError *)error;
    
    +(void)handleNoAccessWithReason:(NSString *)reason;
    
    @end
    

    NetworkClient.m

    /*
     NetworkClient.m
    
     Created by LJ Wilson on 2/3/12.
     Copyright (c) 2012 LJ Wilson. All rights reserved.
     License:
    
     Permission is hereby granted, free of charge, to any person obtaining a copy of this software 
     and associated documentation files (the "Software"), to deal in the Software without restriction, 
     including without limitation the rights to use, copy, modify, merge, publish, distribute, 
     sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is 
     furnished to do so, subject to the following conditions:
    
     The above copyright notice and this permission notice shall be included in all copies or 
     substantial portions of the Software.
    
     THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT 
     NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 
     NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, 
     DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT 
     OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
     */
    
    #import "NetworkClient.h"
    #import "AFHTTPClient.h"
    #import "AFHTTPRequestOperation.h"
    #import "SBJson.h"
    
    NSString * const APIKey = @"APIKEY GOES HERE IF YOU WANT TO USE ONE";
    
    @implementation NetworkClient
    
    +(void)processURLRequestWithURL:(NSString *)url 
                          andParams:(NSDictionary *)params 
                              block:(void (^)(id obj))block {
    
        [self processURLRequestWithURL:url andParams:params syncRequest:NO alertUserOnFailure:NO block:^(id obj) {
            block(obj);
        }];
    }
    
    +(void)processURLRequestWithURL:(NSString *)url 
                          andParams:(NSDictionary *)params 
                        syncRequest:(BOOL)syncRequest
                              block:(void (^)(id obj))block {
        [self processURLRequestWithURL:url andParams:params syncRequest:syncRequest alertUserOnFailure:NO block:^(id obj) {
            block(obj);
        }];
    }
    
    
    +(void)processURLRequestWithURL:(NSString *)url 
                          andParams:(NSDictionary *)params 
                        syncRequest:(BOOL)syncRequest
                 alertUserOnFailure:(BOOL)alertUserOnFailure
                              block:(void (^)(id obj))block {
    
        // Default url goes here, pass in a nil to use it
        if (url == nil) {
            url = @"http://www.mydomain.com/mywebservice";
        }
    
        NSMutableDictionary *dict = [[NSMutableDictionary alloc] initWithDictionary:params];
        [dict setValue:APIKey forKey:@"APIKey"];
    
        NSDictionary *newParams = [[NSDictionary alloc] initWithDictionary:dict];
    
        NSURL *requestURL;
        AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:requestURL];
    
        NSMutableURLRequest *theRequest = [httpClient requestWithMethod:@"POST" path:url parameters:newParams];
    
        __block NSString *responseString = [NSString stringWithString:@""];
    
        AFHTTPRequestOperation *_operation = [[AFHTTPRequestOperation alloc] initWithRequest:theRequest];
        __weak AFHTTPRequestOperation *operation = _operation;
    
        [operation  setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
            responseString = [operation responseString];
    
            id retObj = [responseString JSONValue];
    
            // Check for invalid response (No Access)
            if ([retObj isKindOfClass:[NSDictionary class]]) {
                if ([[(NSDictionary *)retObj valueForKey:@"Message"] isEqualToString:@"No Access"]) {
                    block(nil);
                    [self handleNoAccessWithReason:[(NSDictionary *)retObj valueForKey:@"Reason"]];
                }
            } else if ([retObj isKindOfClass:[NSArray class]]) {
                if ([(NSArray *)retObj count] > 0) {
                    NSDictionary *dict = [(NSArray *)retObj objectAtIndex:0];
                    if ([[dict valueForKey:@"Message"] isEqualToString:@"No Access"]) {
                        block(nil);
                        [self handleNoAccessWithReason:[(NSDictionary *)retObj valueForKey:@"Reason"]];
                    }
                }
            }
            block(retObj);
        } 
                                          failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                                              NSLog(@"Failed with error = %@", [NSString stringWithFormat:@"[Error]:%@",error]);
                                              block(nil);
                                              if (alertUserOnFailure) {
                                                  // Let the user know something went wrong
                                                  [self handleNetworkErrorWithError:operation.error];
                                              }
    
                                          }];
    
        [operation start];
    
        if (syncRequest) {
            // Process the request syncronously
            [operation waitUntilFinished];
        } 
    
    
    }
    
    
    #pragma mark - processFileUpload
    +(void)processFileUploadRequestWithURL:(NSString *)url 
                                 andParams:(NSDictionary *)params 
                                  fileData:(NSData *)fileData 
                                  fileName:(NSString *)fileName
                                  mimeType:(NSString *)mimeType 
                                     block:(void (^)(id obj))block {
    
        // Default url goes here, pass in a nil to use it
        if (url == nil) {
            url = @"http://www.mydomain.com/mywebservice";
        }
    
        NSMutableDictionary *dict = [[NSMutableDictionary alloc] initWithDictionary:params];
        [dict setValue:APIKey forKey:@"APIKey"];
    
        NSDictionary *newParams = [[NSDictionary alloc] initWithDictionary:dict];
        AFHTTPClient *client= [AFHTTPClient clientWithBaseURL:[NSURL URLWithString:url]];  
    
        NSMutableURLRequest *myRequest = [client multipartFormRequestWithMethod:@"POST" 
                                                                           path:@"" 
                                                                     parameters:newParams 
                                                      constructingBodyWithBlock: ^(id <AFMultipartFormData>formData) {
            [formData appendPartWithFileData:fileData name:fileName fileName:fileName mimeType:mimeType];
        }];
    
    
        AFHTTPRequestOperation *_operation = [[AFHTTPRequestOperation alloc] initWithRequest:myRequest];
        __weak AFHTTPRequestOperation *operation = _operation;
        __block NSString *responseString = [NSString stringWithString:@""];
    
        [operation  setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
            responseString = [operation responseString];
    
            id retObj = [responseString JSONValue];
    
            // Check for invalid response (No Access)
            if ([retObj isKindOfClass:[NSDictionary class]]) {
                if ([[(NSDictionary *)retObj valueForKey:@"Message"] isEqualToString:@"No Access"]) {
                    block(nil);
                    [self handleNoAccessWithReason:[(NSDictionary *)retObj valueForKey:@"Reason"]];
                }
            } else if ([retObj isKindOfClass:[NSArray class]]) {
                if ([(NSArray *)retObj count] > 0) {
                    NSDictionary *dict = [(NSArray *)retObj objectAtIndex:0];
                    if ([[dict valueForKey:@"Message"] isEqualToString:@"No Access"]) {
                        block(nil);
                        [self handleNoAccessWithReason:[(NSDictionary *)retObj valueForKey:@"Reason"]];
                    }
                }
            }
            block(retObj);
    
    
        } 
                                          failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                                              NSLog(@"Failed with error = %@", [NSString stringWithFormat:@"[Error]:%@",error]);
                                              block(nil);
    //                                          if (alertUserOnFailure) {
    //                                              // Let the user know something went wrong
    //                                              [self handleNetworkErrorWithError:operation.error];
    //                                          }
    
                                          }];
    
        [operation start];
    
    
    }
    
    
    #pragma mark - Error and Access Handling
    +(void)handleNetworkErrorWithError:(NSError *)error {
        NSString *errorString = [NSString stringWithFormat:@"[Error]:%@",error];
    
        // Standard UIAlert Syntax
        UIAlertView *myAlert = [[UIAlertView alloc] 
                                initWithTitle:@"Connection Error" 
                                message:errorString 
                                delegate:nil 
                                cancelButtonTitle:@"OK" 
                                otherButtonTitles:nil, nil];
    
        [myAlert show];
    
    }
    
    +(void)handleNoAccessWithReason:(NSString *)reason {
        // Standard UIAlert Syntax
        UIAlertView *myAlert = [[UIAlertView alloc] 
                                initWithTitle:@"No Access" 
                                message:reason 
                                delegate:nil 
                                cancelButtonTitle:@"OK" 
                                otherButtonTitles:nil, nil];
    
        [myAlert show];
    
    }
    
    
    @end
    

    Some of this is specific to what I do. All my web services use an APIKey to enhance security and they all do security checks before processing any requests. The network client will return either an NSDictionary or an NSArray depending on what the web service returns (in JSON).

    To use the image upload, you would call this in your VC like this (use as many parameters as you need.:

    NSData *imageData = UIImagePNGRepresentation(myImage);
    NSString *fileName = @"MyFileName.png";
    
    NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:
                                @"Param1", @"Param1Name",
                                @"Param2", @"Param2Name",
                                @"Param3", @"Param3Name", 
                                nil];
    // Uses default URL    
    [NetworkClient processFileUploadRequestWithURL:nil 
                                         andParams:params 
                                          fileData:imageData 
                                          fileName:fileName
                                          mimeType:@"image/png" 
                                                 block:^(id obj) {
        if ([obj isKindOfClass:[NSArray class]]) {
            // Successful upload, do other processing as needed
        }
    }];
    

    Feel free to strip out what you don’t need. Just leave the copyright notice in place.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have this code for uploading files on the server: <tr> <td> <form enctype=multipart/form-data
i doing app for uploading image to php server from android and the php
Greetings, I'm uploading an image to my server using the following code: http://cocoadev.com/index.pl?HTTPFileUploadSample However,
I'm uploading an image from Android to a PHP server. In android I'm encoding
I'm uploading image files from device to a PHP server by converting the file
i am uploading image to s3 server and by php i am making a
I have this file that I am uploading to the server via php file
How should I handle image uploading using PHP? How should I handle the chmod
I am uploading image to server using base64 its working fine if image is
I am building an image uploading website. Images are uploaded to a directory on

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.