Iphone 如何通过POST将图像和字段发送到表单

Iphone 如何通过POST将图像和字段发送到表单,iphone,forms,multipartform-data,Iphone,Forms,Multipartform Data,我有一张这样的表格: <form id="form" action="/post" method="POST" enctype="multipart/form-data"> <input type="file" name="image" /> <input type="text" name="name1" /> <input type="text" name="name2" /> <textarea n

我有一张这样的表格:

<form id="form" action="/post" method="POST" enctype="multipart/form-data"> 
    <input type="file" name="image" /> 
    <input type="text" name="name1" /> 
    <input type="text" name="name2" /> 
    <textarea name="text"></textarea> 
    <input type="text" name="name3" />  
</form>
- (void)sendFields {

UIImage *tempImage = imageViewToPost.image;

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setHTTPMethod:@"POST"];
[request setURL:[NSURL URLWithString:@"http://url/post/"]];


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



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


[body appendData:[@"Content-Disposition: form-data; name=\"image\"; filename=\"photo.png\"\r\n" dataUsingEncoding:NSASCIIStringEncoding]];
[body appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSASCIIStringEncoding]];
[body appendData:[NSData dataWithData:UIImageJPEGRepresentation(tempImage, 90)]];
[body appendData:[[NSString stringWithFormat:@"\r\n%@\r\n",boundary] dataUsingEncoding:NSASCIIStringEncoding]];

[body appendData:[@"Content-Disposition: form-data; name=\"name1\"\r\n\r\n" dataUsingEncoding:NSASCIIStringEncoding]];
[body appendData:[nameToPost dataUsingEncoding:NSUTF8StringEncoding]];

[body appendData:[@"Content-Disposition: form-data; name=\"name2\"\r\n\r\n" dataUsingEncoding:NSASCIIStringEncoding]];
[body appendData:[priceToPost dataUsingEncoding:NSUTF8StringEncoding]];

[body appendData:[@"Content-Disposition: form-data; name=\"text\"\r\n\r\n" dataUsingEncoding:NSASCIIStringEncoding]];
[body appendData:[commentToPost dataUsingEncoding:NSUTF8StringEncoding]];

[body appendData:[@"Content-Disposition: form-data; name=\"name3\"\r\n\r\n" dataUsingEncoding:NSASCIIStringEncoding]];
[body appendData:[coordsToPost dataUsingEncoding:NSUTF8StringEncoding]];


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

NSError *error;
NSURLResponse *response;
NSData *result = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];

NSString *aStr = [[[NSString alloc] initWithData:result encoding:NSASCIIStringEncoding] autorelease];

NSLog(@"Result: %@", aStr);

[request release];    

}
它不起作用。这里怎么了


谢谢大家。

我想分享一些对我有用的代码

- (void)allSet {
    //creating the url request:
    NSURL *cgiUrl = [NSURL URLWithString:@"http://mysite.com/upload.php"];
    NSMutableURLRequest *postRequest = [NSMutableURLRequest requestWithURL:cgiUrl];

    NSString *stringBoundary = [NSString stringWithString:@"0194784892923"];
    NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",stringBoundary];
    [postRequest addValue:contentType forHTTPHeaderField: @"Content-Type"];

    NSData *imageData = UIImageJPEGRepresentation(self.thePicture.photo, 0.5);

    //setting up the body:
    NSMutableData *postBody = [NSMutableData data];
    [postBody appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [postBody appendData:[[NSString stringWithString:@"Content-Disposition: form-data; name=\"category\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
    [postBody appendData:[[NSString stringWithString:@"photos"] dataUsingEncoding:NSUTF8StringEncoding]];
    [postBody appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [postBody appendData:[[NSString stringWithString:@"Content-Disposition: form-data; name=\"format\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
    [postBody appendData:[[NSString stringWithString:@"JSON"] dataUsingEncoding:NSUTF8StringEncoding]];
    [postBody appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [postBody appendData:[[NSString stringWithString:@"Content-Disposition: form-data; name=\"title\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
    [postBody appendData:[[NSString stringWithString:thePicture.title] dataUsingEncoding:NSUTF8StringEncoding]];
    [postBody appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [postBody appendData:[[NSString stringWithString:@"Content-Disposition: form-data; name=\"description\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
    [postBody appendData:[[NSString stringWithString:thePicture.description] dataUsingEncoding:NSUTF8StringEncoding]];
    [postBody appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [postBody appendData:[[NSString stringWithString:@"Content-Disposition: form-data; name=\"latitude\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
    [postBody appendData:[[NSString stringWithFormat:@"%f", [thePicture.latitude floatValue]] dataUsingEncoding:NSUTF8StringEncoding]];
    [postBody appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [postBody appendData:[[NSString stringWithString:@"Content-Disposition: form-data; name=\"longitude\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
    [postBody appendData:[[NSString stringWithFormat:@"%f", [thePicture.longitude floatValue]] dataUsingEncoding:NSUTF8StringEncoding]];
    [postBody appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [postBody appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"photo\"; filename=\"%@.jpg\"\r\n", thePicture.title] dataUsingEncoding:NSUTF8StringEncoding]];
    [postBody appendData:[[NSString stringWithString:@"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
    [postBody appendData:[NSData dataWithData:imageData]];
    [postBody appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]];

    //adding header information:
    [postRequest setHTTPMethod:@"POST"];
    [postRequest setHTTPBody:postBody];

    // create the connection with the request
    // and start loading the data
    theConnection = [[NSURLConnection alloc] initWithRequest:postRequest delegate:self];
    [theConnection start];

    if (theConnection) {
        // Create the NSMutableData that will hold
        // the received data
        // receivedData is declared as a method instance elsewhere
        receivedData=[[NSMutableData data] retain];
    } else {
        // inform the user that the download could not be made
    }   
}

很难,我设置边界和分隔符的方式有问题@“\r\n--%@--\r\n”。试试我的代码,也许我可以解决您的问题。

我建议您查看ASIHTTPRequest库。我用它成功地发布了图片和数据。它的使用和设置非常简单。另外,is内置了一个非常好的异步模型


我在我的应用程序中使用了这段代码,它非常有用

//create request
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];

//Set Params
[request setHTTPShouldHandleCookies:NO];
[request setTimeoutInterval:60];
[request setHTTPMethod:@"POST"];

//Create boundary, it can be anything
NSString *boundary = @"------VohpleBoundary4QuqLuM1cE5lMwCy";

// set Content-Type in HTTP header
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary];
[request setValue:contentType forHTTPHeaderField: @"Content-Type"];

// post body
NSMutableData *body = [NSMutableData data];

//Populate a dictionary with all the regular values you would like to send.
NSMutableDictionary *parameters = [[NSMutableDictionary alloc] init];

[parameters setValue:param1 forKey:@"param1-name"];

[parameters setValue:param2 forKey:@"param2-name"];

[parameters setValue:param3 forKey:@"param3-name"];


// add params (all params are strings)
for (NSString *param in parameters) {
    [body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n", param] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithFormat:@"%@\r\n", [parameters objectForKey:param]] dataUsingEncoding:NSUTF8StringEncoding]];
}

NSString *FileParamConstant = @"imageParamName";

NSData *imageData = UIImageJPEGRepresentation(imageObject, 1);

//Assuming data is not nil we add this to the multipart form
if (imageData)
{
    [body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"image.jpg\"\r\n", FileParamConstant] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[@"Content-Type:image/jpeg\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:imageData];
    [body appendData:[[NSString stringWithFormat:@"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
}

//Close off the request with the boundary
[body appendData:[[NSString stringWithFormat:@"--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];

// setting the body of the post to the request
[request setHTTPBody:body];

// set URL
[request setURL:[NSURL URLWithString:baseUrl]];

[NSURLConnection sendAsynchronousRequest:request
                                   queue:[NSOperationQueue mainQueue]
                       completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {

                           NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response;

                           if ([httpResponse statusCode] == 200) {

                               NSLog(@"success");
                           }

                       }];

“它不起作用”有点宽泛。如果能真实地描述一下它是如何工作的,那就好了。应用程序崩溃了吗?返回的结果是否错误?如果是,您是否确认请求正文是正确的?应用程序不会崩溃。对不起,我的意思是数据没有发送,表单返回的是同一页。