简体   繁体   中英

How to send an HTTP request with multipart data containing a json string and a big file from the file system?


Context

I want to send an HTTP request with multipart body data composed by two segments:

  1. A JSON string containing some metadata
  2. Some file binary data

What I already know

This can be done easily as described in this answer . But what happens in a situation where the file can be potentially large? With this new constraint, we naturally can't encapsulate the data in a NSData object, as it would take a lot of memory resources.

The first idea that anyone familiar with the NSURLRequest class would have is to use the HTTPBodyStream property instead of HTTPBody . But how is it possible to get a stream that would write both JSON and file data segments (as well as the boundaries and the other required HTTP stuff)?

The way out would be to subclass NSInputStream . In fact I've noticed that the AFNetworking framework uses this approach. But from I've heard, there are a lot of undocumented/weird methods to override from the NSStream class, as described here , which, in my humble opinion, sounds like a lot of (potentially dangerous) work needed to achieve something apparently simple.


Question

Is there a way to achieve the desired behaviour? Please consider the following constraints:

  • No third party frameworks
  • Using a clean method (not overriding undocumented methods, as they can change on future SDKs)

You can use my open sourced POSInputStreamLibrary . It provides ability to stream any data you want. The only thing you need to do is to implement POSBlobInputStreamDataSource protocol and use implementation as an argument of POSBlobInputStream .

If you strongly restricted using 3rd party frameworks you can use POSBlobInputStream as an example which implements private API methods to make custom NSInputStream workable.

Feel free to ask any questions about implemetation details and good luck.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM