I want to send file to server path with a paramater "filepath" as one parameter, and file data as another paramater. How do I do it.Here in the following I am appending filepath with data. but I guess it is wrong please help
NSURL *nsurl =[NSURL URLWithString:_urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:nsurl cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
[request setURL:nsurl];
[request setHTTPMethod:#"POST"];
NSString *boundary = #"---------------------------14737809831466499882746641449";
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#",boundary];
[request addValue:contentType forHTTPHeaderField: #"Content-Type"];
NSMutableData *body = [NSMutableData data];
NSData *data = UIImageJPEGRepresentation([UIImage imageNamed:#"Model.png"], 0.0);
NSString *string = [NSString stringWithFormat:#"filepath=%#",_filePath];
NSData *pathData = [string dataUsingEncoding:NSUTF8StringEncoding];
[body appendData:pathData];
//Image
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"image\"; filename=\"%#\"\r\n",#"newFile.png"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:data];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#--\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];
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:returnData options:kNilOptions error:nil];
NSLog(#"%#",dict);
thanks
You can't just do [body appendData:pathData]; at the start. You need to add it with the appropriate boundary and content information. So you should have a number of lines like:
Add the boundary
Add the content info
Add the content data
Add the boundary
And repeat from 2 for each additional piece of data to be added.
Check the spec for information on the appropriate content types and disposition info that needs to be added for each data type (perfect example for you is at the bottom).
Related
I've looked into a good number of articles on how to do a multipart/form-data POST on iOS, but none really explain what to do if there were normal parameters as well as the file upload.
I have used the multipart/form-data POST on iOS & I had written the following code and it is uploading data but not image data
- (void)postWithImage:(NSDictionary *)dictionary
{
NSString *urlString = [NSString stringWithFormat:#"YourHostString"];
NSURL *url = [NSURL URLWithString:urlString];
NSString *boundary = #"----1010101010";
// define content type and add Body Boundry
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#",boundary];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
[request addValue:contentType forHTTPHeaderField: #"Content-Type"];
NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
NSEnumerator *enumerator = [dictionary keyEnumerator];
NSString *key;
NSString *value;
NSString *content_disposition;
while ((key = (NSString *)[enumerator nextObject])) {
if ([key isEqualToString:#"file"]) {
value = (NSString *)[dictionary objectForKey:key];
NSData *postData = UIImageJPEGRepresentation([UIImage imageNamed:value], 1.0);
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"%#\";\r\nfilename=\"screen.png\"\r\n\r\n",value] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:postData];
} else {
value = (NSString *)[dictionary objectForKey:key];
content_disposition = [NSString stringWithFormat:#"Content-Disposition: form-data; name=\"%#\"\r\n\r\n", key];
[body appendData:[content_disposition dataUsingEncoding:NSUTF8StringEncoding]];
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:value options:NSJSONWritingPrettyPrinted error:&error];
[body appendData:jsonData];
//[body appendData:[value dataUsingEncoding:NSUTF8StringEncoding]];
}
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
}
//Close the request body with Boundry
[body appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];
[request addValue:[NSString stringWithFormat:#"%d", body.length] forHTTPHeaderField: #"Content-Length"];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(#"%#", returnString);
}
Can anyone please help me to get why image data is not uploading
I think you should append #"content-Type" before you append real data, like this:
[body appendData:[#"Content-Type: image/png\r\n\r\n"
dataUsingEncoding:NSUTF8StringEncoding]];
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
Image not upload to php server ios 10 It gives error as You did not select a file to upload.
This is the code
- (IBAction)changeProfilePic:(id)sender {
[[sharedClass sharedInstance]showprogressfor:#"Please wait"];
NSString *urlString = [ NSString stringWithFormat:#"http://domain.com/as/web_services/change_user_image?user_id=%#",self.useridString];
UIImage *image= profile_Image;
NSData *imageData = UIImageJPEGRepresentation(image, 0.5);
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:urlString]];
request.timeoutInterval = 10.0f;
request.HTTPMethod = #"POST";
NSString *boundary = #"011000010111000001101001";
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#", boundary, nil];
[request addValue:contentType forHTTPHeaderField:#"Content-Type"];
NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition:form-data; name=\"projectId\"\r\n\r\n"]dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
NSData *stringData = [#"Content-Disposition: form-data;\
name=\"project\";\
fileName=\"photo.jpeg\"\r\n"
dataUsingEncoding:NSUTF8StringEncoding];
[body appendData:stringData];
[body appendData:[#"Content-Type: image/jpeg\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:imageData];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
// NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSDictionary *statusDict = [[NSDictionary alloc]init];
statusDict = [NSJSONSerialization JSONObjectWithData:returnData options:0 error:nil];
NSString *message = [statusDict valueForKey:#"msg"];
[SVProgressHUD dismiss];
NSLog(#" mesaage is %#", message);
}
Try this -
NSString *urlString = [ NSString stringWithFormat:#"http://domine.com/as/web_services/change_user_image?user_id=%#",self.useridString];
NSData *imageData = UIImageJPEGRepresentation(theImage, 0.5);
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:urlString]];
request.timeoutInterval = 10.0f;
request.HTTPMethod = #"POST";
NSString *boundary = #"011000010111000001101001";
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#", boundary, nil];
[request addValue:contentType forHTTPHeaderField:#"Content-Type"];
NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition:form-data; name=\"projectId\"\r\n\r\n"]dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
NSData *stringData = [#"Content-Disposition: form-data;\
name=\"project\";\
fileName=\"photo.jpeg\"\r\n"
dataUsingEncoding:NSUTF8StringEncoding];
[body appendData:stringData];
[body appendData:[#"Content-Type: image/jpeg\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:imageData];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding
Remove space form the url
Copy below code to resolve your issue
NSString *urlString = [NSString stringWithFormat:#"http://domine.com/as/web_services/change_user_image?user_id=%#",self.useridString];
I'm working on uploading an image to a server from last two days as there are tons of questions about uploading an image through AFNetworking and NSURLSession and other methods of uploading all I'm asking is I didn't found a single answer explaining the whole concept about how the things work and what is going on under the hood I searched youtube also all the stuff are available in Swift and trust me no Explanation at all and from my result I found this answer is something that looks familiar to me
//Init the NSURLSession with a configuration
NSURLSessionConfiguration *defaultConfigObject = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration: defaultConfigObject delegate: nil delegateQueue: [NSOperationQueue mainQueue]];
//Create an URLRequest
NSURL *url = [NSURL URLWithString:#"yourURL"];
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];
//Create POST Params and add it to HTTPBody
NSString *params = #"api_key=APIKEY&email=example#example.com&password=password";
[urlRequest setHTTPMethod:#"POST"];
[urlRequest setHTTPBody:[params dataUsingEncoding:NSUTF8StringEncoding]];
//Create task
NSURLSessionDataTask *dataTask = [defaultSession dataTaskWithRequest:urlRequest completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
//Handle your response here
}];
[dataTask resume];
and also the most popular answer about this topic is by User XJones 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:#"%d", [body length]];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
// set URL
[request setURL:requestURL];
But my point is I'm learning on my own and it is very difficult to understand for the beginner without explanation so All I'm asking is an explanation, an Detail explanation about the whole process if someone have a hard time to spend on this question because believe it or not I found this the hardest topic till now because the main reason is there are no tutorials about the whole process and also no explanation at all for beginners if someone can a step now and explain the concept it'll be easier to the students who will learn tomorrow. So anybody who can explain this in detail and how the uploading process works and some steps for the reference will be greatly appreciated.
Note : Consider I Have an API and a Key "image" .
here we gonna look at image uploading along with some **parameters because most of time we upload image along with some parameters such as userId.
Before going deep into our topic let me provide the code for doing the stuff source,All the details we gonna see below are from some other stack overflow threads and some from other sites,i'll provide all the links for your reference.
-(void)callApiWithParameters:(NSDictionary *)inputParameter images:(NSArray *)image imageParamters:(NSArray *)FileParamConstant{
//1
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setHTTPShouldHandleCookies:NO];
[request setTimeoutInterval:30];
[request setHTTPMethod:#"POST"];
//2
NSString *boundary = #"------CLABoundaryGOKUL";
//3
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#", boundary];
[request setValue:contentType forHTTPHeaderField: #"Content-Type"];
//4
NSMutableData *body = [NSMutableData data];
for (NSString *key in inputParameter) {
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"%#\"\r\n\r\n", key] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"%#\r\n", [inputParameter objectForKey:key]] dataUsingEncoding:NSUTF8StringEncoding]];
}
for (int i = 0; i < image.count; i++) {
NSData *imageDatasss = UIImagePNGRepresentation(image[i]);
if (imageDatasss)
{
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"%#\"; filename=\"image.jpg\"\r\n", FileParamConstant[i]] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Type:image/jpeg\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:imageDatasss];
[body appendData:[[NSString stringWithFormat:#"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
}
}
[body appendData:[[NSString stringWithFormat:#"--%#--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
//5
[request setHTTPBody:body];
//6
[request setURL:[NSURL URLWithString:#"http://changeThisWithYourbaseURL?"]];//Eg:#"http://dev1.com/PTA_dev/webservice/webservice.php?"
//7
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response;
//8
if ([httpResponse statusCode] == 200) {
NSDictionary * APIResult =[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
NSLog(#"Response of %#: %#",[inputParameter valueForKey:#"service"],APIResult);
}else{
//9
NSLog(#"%#",error.localizedDescription);
}
}];
}
NOTE: Since it is a broad topic i have provided documentation link for detail info.
We are using ** NSMutableURLRequest** instead of ** NSURLRequest** because we gonna append some data to it.if you need some deep clarification about mutable url request go through this documentation.
setHTTPShouldHandleCookies here we have to decide whether we are going to use cookies or not.To know more about visit
setTimeoutInterval this helps to set a time limit to url request.Add time interval in seconds after the given time,request will be terminated.
setHTTPMethod there are many methods.But we use GET and POST methods in many cases.Difference between POST and GET is here and here
Boundary helps in separating the parameters from each other,so that the server can identify them.The boundary may be anything as your wish feel free to edit it.
Here we use multipart/form-data; boundary= as content type.To know why we are going to this content type look into this thread.
NSMutableData * body we gonna append all the parameters and values to this data and later setHTTPBody to the UrlRequest.
If this is how we call the 'callApiWithParameters' method
- (IBAction)Done:(id)sender{
NSDictionary * inputParameters = [NSDictionary dictionaryWithObjectsAndKeys:
#"1",#"user_id" ,
"XXX",#"name" ,
nil];
NSArray * image = [NSArray arrayWithObjects:[UIImage imageNamed:#"Test"],[UIImage imageNamed:#"Test1"],nil];
NSArray * imageParameters = [NSArray arrayWithObjects:#"img_one",#"img_two",nil];
[self callApiWithParameters:inputParameters images:image imageParamters:imageParameters];
}
then the data (i.e body) will look like this
Content-Type=multipart/form-data; boundary=------CLABoundaryGOKUL
--------CLABoundaryGOKUL
Content-Disposition: form-data; name=user_id
1
--------CLABoundaryGOKUL
Content-Disposition: form-data; name=name
XXX
--------CLABoundaryGOKUL
Content-Disposition: form-data; name=img_one; filename=image.jpg
Content-Type:image/jpeg
//First image data appended here
--------CLABoundaryGOKUL
Content-Disposition: form-data; name=img_two; filename=image.jpg
Content-Type:image/jpeg
//Second image data appended here.
The above give data will clearly explain what going on,all the parameters and keys have been append in the data Here you can find more details about sending multipart/form.
Now simply add the above data to request by [request setHTTPBody:body];
setURL in this method add your base url of your app.
Now all we need to do is make a connection to the server and send the request.Here we use NSURLConnection to send request.Description about NSURLConnection Loads the data for a URL request and executes a handler block on an operation queue when the request completes or fails.
statusCode which helps to find out whether we got successful response from server. If 200 means OK, 500 means Internal Server Error, etc.. more details here .
Handle the error in else case.
FYI I have explained what i can,refer the links for better understanding.
EDIT:
Just change the name in imageParamater array,To satisfy your requirement changed img_one & img_two with image.
- (IBAction)Done:(id)sender{
//Change input parameters as per your requirement.
NSDictionary * inputParameters = [NSDictionary dictionaryWithObjectsAndKeys:
#"1",#"user_id" ,
"XXX",#"name" ,
nil];
NSArray * image = [NSArray arrayWithObjects:[UIImage imageNamed:#"Test"],nil]; //Change Test with your image name
NSArray * imageParameters = [NSArray arrayWithObjects:#"image",nil];//Added image as a key.
[self callApiWithParameters:inputParameters images:image imageParamters:imageParameters];
}
and Change Point 6 with your example base URL,
//6
[request setURL:[NSURL URLWithString:#"http://google.com/files/upload.php?"]];
I think it's Helpful for you...
- (void)sendImageToServer
{
UIImage *yourImage= [UIImage imageNamed:#"image.png"];
NSData *imageData = UIImagePNGRepresentation(yourImage);
NSString *base64 = [imageData base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
NSString *strImage = [NSString stringWithFormat:#"data:image/png;base64,%#",base64];
NSMutableDictionary *dic = [[NSMutableDictionary alloc] initWithObjectsAndKeys:strImage,#"image", nil];
NSError * err;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:0 error:&err];
NSString *UserProfileInRequest = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSData *data=[UserProfileInRequest dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *len = [NSString stringWithFormat:#"%ld", (unsigned long)[data length]];
// Init the URLRequest
NSMutableURLRequest *req = [[NSMutableURLRequest alloc] init];
[req setURL:[NSURL URLWithString:#"http://YOUR_URL"]];
[req setHTTPMethod:#"POST"];
[req setValue:len forHTTPHeaderField:#"Content-Type"];
[req setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[req setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[req setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[req setHTTPBody:data];
NSURLSession *session = [NSURLSession sharedSession];
[[session dataTaskWithRequest:req completionHandler:^(NSData *dt, NSURLResponse *response, NSError *err){
//Response Data
NSMutableDictionary *dic = [NSJSONSerialization JSONObjectWithData:dt options:kNilOptions error:&err];
NSLog(#"%#", [dic description]);
}]resume];
}
Use AFNetworking For this task which will give very easy and reliable solution.
I am a newbie to Objective-C and please let me elaborate what I am doing...
I am trying to upload a file to OneDrive using PUT request.
PUT request must contain
Http Headers
One Drive Documentation
content-length 7919
content-range bytes 0-7918/7919
and with these headers a file will be uploaded
PUT https://sn3302.up.1drv.com/up/fe6987415ace7X4e1eF866337
Content-Length: 7919
Content-Range: bytes 0-7918/7919
<bytes 0-7918 of the file>
Given below are the screen shots of whole PUT request using Chrome POSTMAN
I am trying to make a PUT request with given below headers:
and a file
Could you please guide me how can I do the above using Objective-C
PROBLEM
Everything is working fine with POSTMAN but when I am trying to do it with Objective-C, the file is not getting uploaded and I am getting the given below result:
{"error":{"code":"invalidRequest","message":"Declared fragment length
does not match the provided number of bytes"}}
Objective C code
-(void)uploadFile:(NSString*)uploadUrl
{
NSString *urlString = uploadUrl;
NSData* file = [NSData dataWithContentsOfFile: [#"/Users/username/Desktop/s.sql" stringByExpandingTildeInPath]];
NSString* fileName = #"s.sql";
//
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"PUT"];
NSString *boundary = #"---------------------------14737809831466499882746641449";
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#", boundary];
[request addValue:contentType forHTTPHeaderField: #"Content-Type"];
[request addValue:#"7919" forHTTPHeaderField: #"Content-Length"];
[request addValue:#"bytes 0-7918/7919" forHTTPHeaderField: #"Content-Range"];
NSMutableData *putData = [NSMutableData data];
[putData appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
// Append the file
[putData appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[putData appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"fileupload\"; filename=\"%#\"\r\n", fileName]dataUsingEncoding:NSUTF8StringEncoding]];
[putData appendData:[#"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[putData appendData:[NSData dataWithData:file]];
// Close
[putData appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
// Append
[request setHTTPBody:putData];
NSError *err;
NSURLResponse *response;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
NSString *resSrt = [[NSString alloc]initWithData:responseData encoding:NSASCIIStringEncoding];
}
Thanks to God Finally I found a way. Given below is the edited and working code:
-(void)uploadFile:(NSString*)uploadUrl
{
NSString *urlString = uploadUrl;
NSData* file = [NSData dataWithContentsOfFile: [#"/Users/username/Desktop/s.sql" stringByExpandingTildeInPath]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"PUT"];
[request addValue:#"7919" forHTTPHeaderField: #"Content-Length"];
[request addValue:#"bytes 0-7918/7919" forHTTPHeaderField: #"Content-Range"];
NSMutableData *putData = [NSMutableData data];
[putData appendData:[NSData dataWithData:file]];
// Append
[request setHTTPBody:putData];
NSError *err;
NSURLResponse *response;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
NSString *resSrt = [[NSString alloc]initWithData:responseData encoding:NSASCIIStringEncoding];
NSLog(resSrt);
}
I have to create application for upload video to server in ios. I am using code for upload video which is given below. This code upload small video and working nicely but above 5 mb video can't upload .
- (void)uploadvideo {
NSString *strurl=[NSString stringWithFormat:#"%#",appDele.DRUPAL_SERVICES_URL];
NSString *url=[[NSString alloc]initWithFormat:#"video_upload.php?user_id=%#&node_id=%#",appDele.UserId,appDele.strProductId];
NSString *urlString =[NSString stringWithFormat:#"%#%#",strurl,url] ;
NSLog(#"%#",urlString);
NSString *encodedString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
// setting up the request object now
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:encodedString]];
[request setHTTPMethod:#"POST"];
//[request setTimeoutInterval:10000];
// NSInputStream *videoStream = [[[NSInputStream alloc] initWithData:data1] autorelease];
// [request setHTTPBodyStream:videoStream];
NSString *boundary = [NSString stringWithFormat:#"---------------------------14737809831466499882746641449"];
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#",boundary];
[request addValue:contentType forHTTPHeaderField: #"Content-Type"];
/*
now lets create the body of the post
*/
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\"; filename=\"New.mp4\"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
// NSLog(#"%#New.jpg",appDelegate.MemberId);
[body appendData:[[NSString stringWithFormat:#"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
// [body appendData:data1.length];
[body appendData:[NSData dataWithData:data1]];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n",boundary] 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);
}
Any suggestion on how to upload large video file in ios?
NSURLConnection is quite old, take a look at NSURLSession with it's delegates and blocks. Here's some tutorial, how to migrate from one to another.