iOS, upload file with multipartform-data

試著忘記壹切 提交于 2020-01-01 19:01:15

问题


I would like to upload file to HTTP server. I do it like that right now:

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];
});

I would like to send some additional data in eg. filed "user" with "userId" value. I would like to send some kind of array like:

video[user] = "userId"
video[file] = //file bytes

I know I can do like this using HTTP multipartform-data but I really don know how and I don't understand how it works. Can some one explain me how can I do that and how it works?


回答1:


Try something like this:

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];

Also dont forget to add 'Content-Length' http header field in your request.




回答2:


AFNetowrking is Handy solution for today. Can achieve this easily.

For iOS 6 and above

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);
}];

If project is to iOS 7 and above better to use.

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];

above code samples are from the library documentation. Which can be found at https://github.com/AFNetworking/AFNetworking




回答3:


You can use my library for such network request:

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];

The delegate is set for notification about upload progress.



来源:https://stackoverflow.com/questions/22334690/ios-upload-file-with-multipartform-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!