Pergunta

I have a node.js as backend server. And it has a post method accept a title param and a latitude and longitude param and a image. So, I am not only post a image but with other params together. In the node.js, title -> uitextview's text latitude & longitude - > cllocation and a image.

the node.js corresponding method is a form.

How to use NSURLSessionUploadTask to post them to the server.

Foi útil?

Solução

A file upload with additional parameters will be usually accomplished using a HTTP message whose content type equals multipart/form-data. For reference, see Form-based File Upload in HTML, RFC 1867.

A multipart/form-data body is composed of one or more "parts" which have each a disposition header and an optional content type header. One part contains the data of the file along with a corresponding content type header, and the other part (or several parts) contain the parameters. The part containing parameters, may have a content type of application/x-www-form-urlencoded where the body consists of the encoded parameters, or perhaps JSON or whatever is supported by the server. Each single parameter may also be represented as a separate part.

The difficulty here is the proper composition of the HTTP message whose body is a set of parts. Cocoa or iOS does not have direct support for composing a multipart form data message. That is, you may try to compose this message out of the parts yourself, by hand.

However this technique is elaborated and error prone, and if you strive to be correct regarding all and relevant HTTP and MIME specifications you need to read through virtually 100 RFCs and understand them thoroughly and then painstakingly apply that specification in the underlying implementation. (Please, do yourself a favor and don't try this!)

While at the end of the day, it may turn out that it is relatively easy to compose a message out of parts yourself (there are few examples here on SO which demonstrates this), there's also the tricky part when you want utilize NSStreams as "virtual" body of a part, say a file stream which you want to use, since creating a NSData object seems too costly regarding the amount of allocated memory.

So, when you can afford to compose the complete body (consisting of multiple parts) of the HTTP message into one NSData object, the effort to accomplish this may be moderately low. Otherwise, if you cannot hold the image data and the whole body into memory, I would strongly recommend to use a third party library which is capable to use NSStream as "data sources" for body parts.

How to compose a multipart/form-data message is described in more detail in my answer here. There are also countless related questions on SO.

For a third party library which supports to construct body parts using a NSStream as data source, take a look at AFNetworking, possibly also MKNetworkKit (without supporting NSURLSession yet)

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top