如何使用NSURLConnection上传文件和其他参数

时间:2012-06-13 22:32:05

标签: iphone cocoa-touch ipad nsurlconnection nsmutableurlrequest

我正在使用NSURLConnection将相同的数据(NSString)发送到服务器,我想添加一个图片或文件,以便了解内容类型的值?

编码

- (NSData *)encodingData:(NSMutableDictionary *)dictionary
{
    NSMutableArray *arrayPosts = [[NSMutableArray alloc] init];
    [dictionary enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
         NSString *encodedKey = [key stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
         NSString *encodedValue = [obj stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        [arrayPosts addObject:[NSString stringWithFormat:@"%@=%@",encodedKey,encodedValue]];
    }];
    NSString *encodedArrayPosts = [arrayPosts componentsJoinedByString:@"&"];
    return [encodedArrayPosts dataUsingEncoding:NSUTF8StringEncoding];
}

发送数据

- (void)startAsyncRequest
{
   // Enable the network activity indicator in the status bar
   [self enableActivityIndicatorInStatusBar];

   // Setting of the request
   NSMutableURLRequest *urlRequest = [[NSMutableURLRequest alloc] initWithURL:self.url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:20.0];
   [urlRequest setHTTPMethod:self.method];
   [urlRequest setHTTPBody:[self encodingData:self.dictionaryPosts]];

   // Send the request
   NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:urlRequest delegate:self];

   if (connection) {
      // Connection succeded 
     self.receiveData = [NSMutableData data];
   } else {
      // Connection Failed
      self.error = @"Connection Failed";
      // Inform the user that the connection failed
      [self.delegate requestFailed:self];
   }
}

1 个答案:

答案 0 :(得分:4)

您需要将数据传递到服务器中的流类型

public InsertImage(Stream stream)

然后解析流类型。

这是使用某些边界构建请求的方法

- (NSURLRequest *)buildRequest:(NSData *)paramData fileName:(NSString *)name {
    NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
    NSString *charset = (NSString *)CFStringConvertEncodingToIANACharSetName(CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding));
    [request setURL:self.url];
    [request setHTTPMethod:self.method];

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

    // Sample Key Value for data
    [tempPostData appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n", @"Key_Param"] dataUsingEncoding:NSUTF8StringEncoding]];
    [tempPostData appendData:@"Value_Param"] dataUsingEncoding:NSUTF8StringEncoding]];
    [tempPostData appendData:[endBoundary dataUsingEncoding:NSUTF8StringEncoding]];

    // Sample file to send as data
    [tempPostData appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"userfile\"; filename=\"%@\"\r\n", name] dataUsingEncoding:NSUTF8StringEncoding]];
    [tempPostData appendData:[[NSString stringWithString:@"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
    [tempPostData appendData:paramData];
    [tempPostData appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [request setHTTPBody:tempPostData];
    return request;
}

您应该在服务器端获取流类型数据并解析它,您可以获得您传递的密钥的值,例如Key_Param,以及您发送的文件的名称(fileName)。