iPhone使用AFNetworking上传多部分文件

时间:2013-03-14 13:30:39

标签: ios objective-c api file-upload

在我的iOS应用程序中,我想使用NSMutableURLRequest为多部分文件上传带有Java API的文件。这是显示参数的表单。

  <form action="API_URL" encType='multipart/form-data' method=post>
            <input type=file name="files">
            <input type=submit value="Upload Attempt Files">

编辑表格2

       <form action='URL' method="post" encType='multipart/form-data'>
<input name="key1" value='123'>
<input name="key2" value='asdf'>
<input name="key3" value='qwerty'>
<input name="key4" value='aaa'>
<input name="key5" value='aaa'>
<input name="key6" value='false'>
<input type="file"  name="files">
<input type=submit value="Create Forum Posts">
   </form>        

我怎样才能做到这一点?

Question显示如何在iOS中使用AFNetworking上传多部分文件(目标c)。但是我没有按照我正在使用的形式来设置参数。

3 个答案:

答案 0 :(得分:81)

查看您的HTML,name的{​​{1}}为<input type=file>,因此,您可以使用files作为@"files"参数{ {3}}方法。例如,使用appendPartWithFileData

name

(对于AFNetworking 1.x和2.x语法,请参阅此答案的修订历史记录。)

答案 1 :(得分:4)

-(void) makePhotoUploadRequest{

    NSArray *keys = [[NSArray alloc]initWithObjects:@"UserID", @"CompanyName" ,@"Location",@"Latitude",@"Longitude",@"Tagline",@"Goals",@"ColorName",nil];
    NSArray *values =[[NSArray alloc]initWithObjects:@"103",@"queppelin",@"Jaiur",@"11.3" ,@"12.3",@"Let's do it",@"Let's do it",@"Let's do it", nil];
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];

    NSURL *baseUrl = [NSURL URLWithString:[NSString stringWithFormat:@"%@%@/%@/RegisterCompanyUser",serverRequest,serverPort,serverName]];

    NSString *charset = (NSString *)CFStringConvertEncodingToIANACharSetName(CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding));
    [request setURL:baseUrl];
    [request setHTTPMethod:@"POST"];

   NSString *boundary = @"0xKhTmLbOuNdArY";
    NSString *endBoundary = [NSString stringWithFormat:@"\r\n--%@\r\n", boundary];

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

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


           for(int i=0;i<keys.count;i++){
               NSString *str = values[i];
               NSString *key =keys[i];
               NSLog(@"Key Value pair: %@-%@",key,str);
               [tempPostData appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n", key] dataUsingEncoding:NSUTF8StringEncoding]];
               [tempPostData appendData:[str dataUsingEncoding:NSUTF8StringEncoding]];
              // [tempPostData appendData:[@"\r\n--%@\r\n",boundary dataUsingEncoding:NSUTF8StringEncoding]];
                   [tempPostData appendData:[endBoundary dataUsingEncoding:NSUTF8StringEncoding]];

        }





    // Sample file to send as data
    [tempPostData appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"Image\"; filename=\"%@\"\r\n", @"company-logo.png"] dataUsingEncoding:NSUTF8StringEncoding]];
    [tempPostData appendData:[[NSString stringWithString:@"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];

    UIImage *myImageObj = [UIImage imageNamed:@"company-logo.png"];
    NSData *mydata= UIImagePNGRepresentation(myImageObj);
    NSLog(@"Image data:%d",mydata.length);
        [tempPostData appendData:mydata];

    [tempPostData appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [request setHTTPBody:tempPostData];

    NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
    if( theConnection )
    {
       dataWebService = [NSMutableData data] ;
        NSLog(@"request uploading successful");
    }
    else
    {
        NSLog(@"theConnection is NULL");
    }


}

答案 2 :(得分:0)

您可以使用以下代码使用anetworking 3.x在多部分请求中发送图像和n个参数

 AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
 //manager.responseSerializer = [AFHTTPResponseSerializer serializer]; // uncomment this line when the server is not returning JSON

[manager POST: urlString parameters: nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
    [formData appendPartWithFileData:imageData
                                name:@"file"
                            fileName:imageName mimeType:@"image/jpeg"];
        for (NSString *key in parameters) {
            [formData appendPartWithFormData:[[[parameters objectForKey:key] description] dataUsingEncoding:NSUTF8StringEncoding] name:key];
        }

    // etc.
} progress:nil success:^(NSURLSessionDataTask *task, id responseObject) {
    NSLog(@"Response: %@", responseObject);
} failure:^(NSURLSessionDataTask *task, NSError *error) {
    NSLog(@"Error: %@", error);
}];