cocoapostasiformdatarequest

multipart POST request directly in ASIFormDataRequest


So you think it would be easy to find a direct example of POST information to ASIFormDataRequest, but I havent found a 1:1 in these formats. Here's the POST request I want to send:

POST /fileXfer HTTP/1.1
Content-Type: multipart/form-data; boundary=AaB03x
Content-Length: 200
AppID:myID
TransferID:abcd1234

-- AaB03x
Content-Disposition: form-data; name="data"; filename="xxx"
Content-Type: application/octet-stream
Content-Length: 100

... contents of file ...

--AaB03x--

EDIT:

Turns out my problems were more with the server receiving the data. But this is what I ended up with!

NSURL *url = [NSURL URLWithString:@"http://IP:PORT/fileXfer"];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setPostFormat:ASIMultipartFormDataPostFormat];

//Sets headers of POST
[request addRequestHeader:@"X-Application-Id" value:@"myID"];
[request addRequestHeader:@"X-Transfer-Id" value:@"abcd1234"];

//Sets data
NSData *fileData = [NSData dataWithContentsOfFile:kEncryptedFilePath];
[request setData:fileData withFileName:@"xxx" andContentType:@"application/octet-stream" forKey:@"data"];

[request setDelegate:self];
[request startAsynchronous];

I also added the following line to ASIFormDataRequest's buildMultipartFormDataPostBody where Content-Disposition and Content-Type are set:

[self appendPostString:[NSString stringWithFormat:@"Content-Length: %lu\r\n\r\n", [data length]]];`

I'm not sure if there's an easier way to add that line directly from the request, but out of the things I tried, this seemed to be the one that worked.


Solution

  • Rather than building the HTTP body manually, which may lead to errors, you should better use the methods provided by ASIFormDataRequest.

    NSURL *url = [NSURL URLWithString:@"http://IP:PORT/fileXfer"];
    ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
    
    [request addRequestHeader:@"X-Application-Id" value:@"myID"];
    [request addRequestHeader:@"X-Transfer-Id" value:@"abcd1234"];
    
    [request setData:[self fileData] withFileName:@"xxx" andContentType:@"application/octet-stream" forKey:@"data"];
    
    [request setDelegate:self];
    [request startAsynchronous];