Question

I currently am uploading files via HTTP Post, using [body appendData: [NSData dataWithData:data]]; where data is my NSMutableData representation of the file.

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

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

// Set up web request with HTTP post headers for 1 form field which is the image
NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:@"Content-Disposition: form-data; name=\"userfile\"; filename=\".jpg\"\r\n"] 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", boundary] dataUsingEncoding: NSUTF8StringEncoding]];

// Set the body
[request setHTTPBody: body];

Due to memory limitations, I have read that its best to upload using setHTTPBodyStream and passing in the location of the file on disk - how would I go about setting other attributes such as the content disposition using this method?

Was it helpful?

Solution

You have to prepare a file containing the entire HTML request body, including the multipart boundaries, the content type and disposition, and use that for setHTTPBodyStream.

There are alternatives (subclassing NSInputStream, which seems to be a bit tricky, and 3rd party libraries such as ASIHTTPRequest). This post provides more information and links.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top