【发布时间】:2014-03-11 19:26:33
【问题描述】:
我想上传文件到 HTTP 服务器。我现在就是这样做的:
NSString *boundary = @"*****";
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:@"http://someUploadScript.php"]];
[request setHTTPMethod:@"POST"];
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary];
[request setValue:contentType forHTTPHeaderField: @"Content-Type"];
[request setValue:@"Keep-Alive" forHTTPHeaderField: @"Connection"];
dispatch_async(queue, ^{
NSMutableData *postbody = [NSMutableData data];
[postbody appendData:[[NSString stringWithFormat:@"--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"userfile\"; filename=\"video.mp4\"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
NSString* outputPath = @"somePathToFile";
NSData *data = [NSData dataWithContentsOfFile:outputPath];
[postbody appendData:data];
[postbody appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[[NSString stringWithFormat:@"--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:postbody];
previousBytesWritten = 0;
connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];
});
我想发送一些额外的数据,例如。用“userId”值提交“用户”。我想发送某种数组,例如:
video[user] = "userId"
video[file] = //file bytes
我知道我可以使用 HTTP multipartform-data 做到这一点,但我真的不知道怎么做,也不明白它是如何工作的。谁能解释一下我该怎么做以及它是如何工作的?
【问题讨论】:
标签: ios http multipartform-data