1

I am trying to upload a file with the following method:

- (void)uploadWithTarget:(NSString *)url andFileData:(NSData *)file andMD5Checksum:(NSString *)checksum
 {


NSURLSessionConfiguration *defaultConfigObject = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration: defaultConfigObject delegate: self delegateQueue: [NSOperationQueue mainQueue]];

NSURL * urll = [NSURL URLWithString:url];
NSMutableURLRequest * urlRequest = [NSMutableURLRequest requestWithURL:urll];
[urlRequest setHTTPMethod:@"POST"];
[urlRequest addValue:checksum forHTTPHeaderField:@"Md5Hash"];
[urlRequest addValue:@"Keep-Alive" forHTTPHeaderField:@"Connection"];
[urlRequest addValue:@"xml" forHTTPHeaderField:@"Content-Type"];
[urlRequest setHTTPBody:file];


NSURLSessionDataTask * dataTask = [defaultSession dataTaskWithRequest:urlRequest];
[dataTask resume];


}

Delegate:

- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask
didReceiveData:(NSData *)data
{
NSString * str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"Received String %@",str);
}

But i always get the error from my server that there isn´t a file attached! What´s wrong?

Clay Bridges
  • 11,602
  • 10
  • 68
  • 118
davidOhara
  • 1,008
  • 5
  • 17
  • 39
  • how do check checksum after uploading completes – Mr.G Apr 23 '15 at 11:03
  • 1
    The content type of your HTTP request needs to be multipart/form-data. Also the body must be formed as a multipart request. You can find a tutorial here: http://web.archive.org/web/20140311092840/http://zcentric.com/2008/08/29/post-a-uiimage-to-the-web/ – Janos Jan 23 '14 at 15:24
  • That looks good, but how to get dynamic NSSTrings into filename here: [body appendData:[[NSString stringWithString:@"Content-Disposition: form-data; name="userfile"; filename="ipodfile.jpg"rn"] dataUsingEncoding:NSUTF8StringEncoding]]; – davidOhara Jan 23 '14 at 15:53
  • Using for example NSString's stringWithFormat – Janos Jan 23 '14 at 16:00

1 Answers1

0

If you are using Swift, checkout Just. Example from the readme file:

//  talk to registration end point
Just.post(
    "http://justiceleauge.org/member/register",
    data: ["username": "barryallen", "password":"ReverseF1ashSucks"],
    files: ["profile_photo": .URL(fileURLWithPath:"flash.jpeg", nil)]
) { (r)
    if (r.ok) { /* success! */ }
}
Daniel Duan
  • 2,493
  • 4
  • 21
  • 24