如何使用Objective-C iPhone SDK连同一些POST变量一起发送文件? [英] How to send file along some POST variables with Objective-C iPhone SDK?

查看:82
本文介绍了如何使用Objective-C iPhone SDK连同一些POST变量一起发送文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道{insert_title_here}吗?

I'd like to know {insert_title_here}?

我使用这种方法,但是没有成功:

I use this method, but with no success:

    //string data
    NSString *post = @"message=helloWorld";
    NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];

    //file data
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *fullPathToFile = [documentsDirectory stringByAppendingPathComponent:@"ImageFile.png"];
    NSData *imageData = [[NSData alloc] initWithContentsOfFile:fullPathToFile];

    //request
    NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
    [request setURL:@"http://www.example.com/"];
    [request setHTTPMethod:@"POST"];
    NSString *boundary = @"---------------------------14737809831466499882746641449";
    NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
    [request addValue:contentType forHTTPHeaderField: @"Content-Type"];

    //POST body
    NSMutableData *postbody = [NSMutableData data]; 

    //append string data
    [postbody appendData:postData];

    //append file
    [postbody appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];

    [postbody appendData:[[NSString stringWithString:@"Content-Disposition: form-data; name=\"iconFile\"; filename=\"ImageFile.png\"\r\n"] 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",boundary] dataUsingEncoding:NSUTF8StringEncoding]];

    [request setHTTPBody:postbody];

    //set content length
    NSString *postLength = [NSString stringWithFormat:@"%d", [postbody length]];
    [request setValue:postLength forHTTPHeaderField:@"Content-Length"];

    //send and receive
    NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];

有什么建议吗?

推荐答案

似乎您正在附加文件.

检查在iPhone编程中将文件上传到HTTP服务器

这篇关于如何使用Objective-C iPhone SDK连同一些POST变量一起发送文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆