0

我想知道如何在同一个 NSMutableRequest 中上传图像和一些数据

- (void)startAsyncRequest
{
   // Setting of the request
   NSMutableURLRequest *urlRequest = [[NSMutableURLRequest alloc] initWithURL:self.url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:20.0];
   [urlRequest setHTTPMethod:self.method];
   [urlRequest setHTTPBody:data];

   // 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];
   }
}
4

1 回答 1

0

您应该模拟一个表单帖子,例如:

NSString *boundary = [NSString stringWithString:@\"---------------------------14737809831466499882746641449\"];  
NSString *contentType = [NSString stringWithFormat:@\"multipart/form-data; boundary=%@\",boundary];  
[request addValue:contentType forHTTPHeaderField: @\"Content-Type\"];
/* 
 now lets create the body of the post 
 */  
NSMutableData *body = [NSMutableData data];  

//parameter1  
[body appendData:[[NSString stringWithFormat:@\"\r\n--%@\r\n\",boundary] dataUsingEncoding:NSUTF8StringEncoding]];   
[body appendData:[[NSString stringWithFormat:@\"Content-Disposition: form-data; name=\\"guid\\"\r\n\r\n%@\", [Settings sharedInstance].uploadID] dataUsingEncoding:NSUTF8StringEncoding]];  
[body appendData:[[NSString stringWithFormat:@\"\r\n--%@\r\n\",boundary] dataUsingEncoding:NSUTF8StringEncoding]];  
//Image  
[body appendData:[[NSString stringWithFormat:@\"Content-Disposition: form-data; name=\\"filMyFile\\"; filename=\\"%@\\"\r\n\", fileName] dataUsingEncoding:NSUTF8StringEncoding]];  
[body appendData:[[NSString stringWithString:@\"Content-Type: image/png\r\n\r\n\"] dataUsingEncoding:NSUTF8StringEncoding]];  
[body appendData:[NSData dataWithData:dataObj]];  
[body appendData:[[NSString stringWithFormat:@\"\r\n--%@--\r\n\",boundary] dataUsingEncoding:NSUTF8StringEncoding]];  

// setting the body of the post to the reqeust  
[request setHTTPBody:body];
于 2012-10-11T01:44:17.710 回答