首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >iOS,使用多部分格式数据上传文件

iOS,使用多部分格式数据上传文件
EN

Stack Overflow用户
提问于 2014-03-12 03:26:33
回答 3查看 13.9K关注 0票数 2

我想上传文件到HTTP服务器。我现在就这么做:

代码语言:javascript
复制
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];
});

我想发送一些额外的数据,例如。已将"user“与"userId”值一起归档。我想要发送某种类型的数组,例如:

代码语言:javascript
复制
video[user] = "userId"
video[file] = //file bytes

我知道使用HTTP multipartform-data可以做到这一点,但我真的不知道怎么做,也不明白它是如何工作的。有人能解释一下我该怎么做吗?它是如何工作的?

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2014-03-12 04:16:37

尝试如下所示:

代码语言:javascript
复制
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]];

// Adding one more field:
// append boundary
[postbody appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
// setting up form-data header, if it is text no 'filename' needed
[postbody appendData:[@"Content-Disposition: form-data; name=\"userId\"\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
// appending userId value
[postbody appendData:[_userId dataUsingEncoding:NSUTF8StringEncoding]];

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

[request setHTTPBody:postbody];

另外,不要忘记在请求中添加“Content-Length”http头字段。

票数 5
EN

Stack Overflow用户

发布于 2015-03-14 22:03:50

对于今天来说,AFNetowrking是一个方便的解决方案。可以很容易地实现这一点。

适用于iOS 6及更高版本

代码语言:javascript
复制
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *parameters = @{@"foo": @"bar"};
NSURL *filePath = [NSURL fileURLWithPath:@"file://path/to/image.png"];
[manager POST:@"http://example.com/resources.json" parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
    [formData appendPartWithFileURL:filePath name:@"image" error:nil];
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
    NSLog(@"Success: %@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"Error: %@", error);
}];

如果项目是iOS 7或更高版本,最好使用。

代码语言:javascript
复制
NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:@"http://example.com/upload" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        [formData appendPartWithFileURL:[NSURL fileURLWithPath:@"file://path/to/image.jpg"] name:@"file" fileName:@"filename.jpg" mimeType:@"image/jpeg" error:nil];
    } error:nil];

AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
NSProgress *progress = nil;

NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithStreamedRequest:request progress:&progress completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
    if (error) {
        NSLog(@"Error: %@", error);
    } else {
        NSLog(@"%@ %@", response, responseObject);
    }
}];

[uploadTask resume];

上面的代码示例来自于库文档。可在https://github.com/AFNetworking/AFNetworking上找到

票数 3
EN

Stack Overflow用户

发布于 2015-03-04 17:39:49

您可以使用my library来处理此类网络请求:

代码语言:javascript
复制
WebRequest *request = [[WebRequest alloc] initWithPath:@"...documents/create.json"];
request.delegate = delegate;
request.notificationName = @"NotificationDocumentUploaded";

NSMutableData *body = [NSMutableData data];
NSString *boundary = @"TeslaSchoolProjectFormBoundary";

[body appendPartName:@"document[name]" value:@"Test" boundary:boundary];
[body appendPartName:@"document[description]" value:@"This is a description" boundary:boundary];
[body appendPartName:@"document[category]" value:@"Drama" boundary:boundary];
...
[body appendPartName:@"commit" value:@"Save" boundary:boundary];
NSData *fileData = [[NSData alloc] initWithContentsOfURL:someFileURL];
[body appendPartFile:fileName name:@"document[file]" data:fileData mimeType:mimeType boundary:boundary];
[body appendData:[[NSString stringWithFormat:@"--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];

[request setHTTPBody:body];

NSString *bodyLength = [NSString stringWithFormat:@"%lu",(unsigned long)[body length]];
[request addValue:bodyLength forHTTPHeaderField:@"Content-Length"];

// optional
[request addValue:@"gzip,deflate,sdch" forHTTPHeaderField:@"Accept-Encoding"];
[request addValue:@"max-age=0" forHTTPHeaderField:@"Cache-Control"];
[request addValue:@"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8" forHTTPHeaderField:@"Accept"];
[request addValue:@"en-US,en;q=0.8,hr;q=0.6,it;q=0.4,sk;q=0.2,sl;q=0.2,sr;q=0.2" forHTTPHeaderField:@"Accept-Language"];

[request setValue:[NSString stringWithFormat:@"multipart/form-data; charset=utf-8; boundary=%@", boundary] forHTTPHeaderField:@"Content-Type"];

[request setHTTPMethod:@"POST"];
[WebRequestProcessor process:request];

代理被设置为通知上传进度。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/22334690

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档