zumzum
zumzum

Reputation: 20198

Upload NSData in multipart from stream?

I want to upload some NSData to a server, I want to do so using the multipart approach. There are several questions on stack about this, but, I want to be able to handle large files on iOS, so fully loading the asset in memory is not always an option, I would like to know if I can stream the file from disk, into a multipart request.

This: File Upload to HTTP server in iphone programming

is one of the many questions I found, but as you can see they load the data in memory and then stick it into the request at once:

[postbody appendData:[NSData dataWithData:YOUR_NSDATA_HERE]];

Any idea?

Upvotes: 0

Views: 340

Answers (2)

rob mayoff
rob mayoff

Reputation: 385860

If you're using NSURLSession, then you can use uploadTaskWithRequest:fromFile: to upload the contents of a file, and the task is responsible for reading the file. Perhaps the task reads the file in chunks.

If you don't have the data in a file, you can use uploadTaskWithStreamedRequest:. You provide the task with a delegate that implements URLSession:task:needNewBodyStream: to provide an input stream to the task. You can implement NSInputStream to returns chunks of data.

Upvotes: 0

Greg Brown
Greg Brown

Reputation: 3254

Have you looked into the options you can pass to NSData's dataWithContentsOfURL:options:error: method? I haven't tried it myself, but it seems like NSDataReadingMappedIfSafe might be of use:

https://developer.apple.com/library/ios/documentation/Cocoa/Reference/Foundation/Classes/NSData_Class/#//apple_ref/c/tdef/NSDataReadingOptions

Upvotes: 0

Related Questions