Uploading a file using NSUrlRequest results in Zer

2019-06-28 03:11发布

I'm trying to do a simple file upload using objective c and NSUrlRequest.

My current (more or less googled and put together) code:

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:@"http://127.0.0.1:8000/api/upload/"]];
[request setHTTPMethod:@"POST"];


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


NSMutableData *postData = [NSMutableData data]; 
[postData appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];

// Append the Usertoken
[postData appendData:[[NSString stringWithString:@"Content-Disposition: form-data; name=\"token\"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[postData appendData:[[NSString stringWithString:@"Content-Type: application/json\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[postData appendData:[[NSString stringWithFormat:@"%@", token] dataUsingEncoding:NSUTF8StringEncoding]];

// Append the file
[postData appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];    
[postData appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"fileupload\"; filename=\"%@\"\r\n", file]dataUsingEncoding:NSUTF8StringEncoding]];
[postData appendData:[[NSString stringWithString:@"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];

// Close
[postData appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];

// Append
[request setHTTPBody:postData];

All uploaded files having Zero Bytes filesize. The serverside part is working correctly. Tested with cURL.

Did i forget something?

1条回答
【Aperson】
2楼-- · 2019-06-28 03:23

Found my mistake. Was a very simple one, happened because of my lack of knowledge about http.

I forgot to append the file data after the octet-stream

NSData *photo = [[NSFileManager defaultManager] contentsAtPath:file];

// Append the file
[postData appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];    
[postData appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"fileupload\"; filename=\"%@\"\r\n", file]dataUsingEncoding:NSUTF8StringEncoding]];
[postData appendData:[[NSString stringWithString:@"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[postData appendData:[NSData dataWithData:photo]];
查看更多
登录 后发表回答