xcode - 将带有表单参数的图像上载到Web服务器

时间:2014-06-21 11:26:37

标签: xcode http-post multipartform-data nsmutableurlrequest

我想将一个带有3个参数的图像上传到网络服务器上,不成功。

我的代码是:

-(IBAction)uploadPhoto:(id)sender{


        NSString *urlString = @"https://urlwebservice";
        NSURL *url = [NSURL URLWithString:urlString];

        NSString *serverName = @"user";
        NSString *serverPassword = @"password";

        // create a plaintext string in the format username:password
        NSString *authStr = [NSString stringWithFormat:@"%@:%@", serverName, serverPassword];

        NSData *authData = [authStr dataUsingEncoding:NSUTF8StringEncoding];
        NSString *authValue = [NSString stringWithFormat:@"Basic %@", [Base64 encode:authData ]];

        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL: url
                                                               cachePolicy: NSURLRequestUseProtocolCachePolicy
                                                           timeoutInterval: 10];
        [request setHTTPMethod:@"POST"];
        [request setValue:authValue  forHTTPHeaderField:@"Authorization"];


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

        //image
        [postBody appendData:[[NSString stringWithFormat:@"--%@\r\n", stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]];
        [postBody appendData:[@"Content-Disposition: form-data; name=\"file\"; filename=\"item.jpg\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
        [postBody appendData:[@"Content-Type: image/jpg\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
        [postBody appendData:[@"Content-Transfer-Encoding: binary\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];

        // get the image data from main bundle directly into NSData object
        NSData *imgData = UIImageJPEGRepresentation(photo, 0.2);
        // add it to body
        [postBody appendData:imgData];
        [postBody appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
        NSLog(@"message added");
        // final boundary
        [postBody appendData:[[NSString stringWithFormat:@"--%@--\r\n", stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]];

        //PARAMETERS body
        NSString *nombre = @"parameter_name" ;
        NSString *valoracion = @"2";
        NSString *precio = @"12" ;

        //nombre
        [postBody appendData:[[NSString stringWithFormat:@"--%@\r\n", stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]];
        [postBody appendData:[@"Content-Disposition: form-data; name=\"nombre\"\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
        [postBody appendData:[nombre dataUsingEncoding:NSUTF8StringEncoding]];
        [postBody appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];

        //VAL
        [postBody appendData:[[NSString stringWithFormat:@"--%@\r\n", stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]];
        [postBody appendData:[@"Content-Disposition: form-data; name=\"nombre\"\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
        [postBody appendData:[valoracion dataUsingEncoding:NSUTF8StringEncoding]];
        [postBody appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];

        //PRECIO
        [postBody appendData:[[NSString stringWithFormat:@"--%@\r\n", stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]];
        [postBody appendData:[@"Content-Disposition: form-data; name=\"nombre\"\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
        [postBody appendData:[precio dataUsingEncoding:NSUTF8StringEncoding]];
        [postBody appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];


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

        NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
        NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
        NSLog(@"RETURN from  method:   %@",returnString);


}

成功响应的等效Java客户端方法是:

  try {
                FormDataMultiPart form = new FormDataMultiPart().field("file", new File("c:\\1943.jpg"), MediaType.MULTIPART_FORM_DATA_TYPE)
                        .field("nombre", "parameter_name")
                        .field("valoracion", "4")
                        .field("precio", "13,45 €")


                WebResource webResource = Client.create().resource("https://webservice");
                webResource.header("Authorization", "Basic " + Base64.encodeBase64String(StringUtils.getBytesUtf8("user:password")));
                webResource.type(MediaType.MULTIPART_FORM_DATA)
                           .accept(MediaType.TEXT_PLAIN)
                           .post(form);

            }

任何人都知道在objective-c代码中我的错误是什么?

提前致谢

1 个答案:

答案 0 :(得分:0)

乍一看,我看到: 你没有发送" Content-Length"发布数据。

这是我的工作代码,用于在服务器上发送带有参数的图像:

NSMutableURLRequest *myPost = [NSMutableURLRequest requestWithURL:myUrl];
[myPost setHTTPMethod:@"POST"];

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

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


for (NSString * key in postDict) {
    [postBody appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n",[key dataUsingEncoding:NSUTF8StringEncoding]] dataUsingEncoding:NSUTF8StringEncoding]];
    [postBody appendData:[postDict[key] dataUsingEncoding:NSUTF8StringEncoding]];
    [postBody appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]];
}
if(imageData!=nil){
    [postBody appendData:[@"Content-Disposition: form-data; name=\"AVATAR_FILE\"; filename=\"test.png\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
    [postBody appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
    [postBody appendData:imageData];
    [postBody appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]];
}
[myPost setHTTPBody:postBody];
NSString *tmp = [NSString stringWithFormat:@"%d",[postBody length]];
[myPost setValue:tmp forHTTPHeaderField:@"Content-Length"];
[[NSURLConnection alloc] initWithRequest:myPost delegate:self];

但我建议使用库https://github.com/AFNetworking/AFNetworking - 它更容易,更方便