objective-c - 不上传文件的内容

时间:2013-07-17 23:27:00

标签: iphone objective-c upload

我想将本地字(或rtf)文件上传到我的服务器。上传没有内容的文件。没有错误代码或任何东西..

NSString *urlString = @"http://myserver.com/upload-c.php";
NSString *filename=@"xx.docx";

NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"xx.docx"]];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:@"POST"];

NSString *boundary = [NSString stringWithString:@"---------------------------14737809831466499882746641449"];
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:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"userfile\"; filename=\"%@\"\r\n",filename]] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:@"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:data]];

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

NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnString = [[[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding] autorelease];

NSLog(@"%@",returnString);

1 个答案:

答案 0 :(得分:1)

一个明显的问题是如何初始化data变量。

假设“xx.docx”是您要上传的文件,则有两个问题。

  1. 您需要指定文件的完整路径,而不仅仅是文件名。
  2. 由于您是从文件路径创建NSURL,因此您需要使用fileURLWithPath:,而不是URLWithString:
  3. 编辑:根据您的评论,该文件位于应用程序的资源包中。要获得它的完整路径,你应该这样做:

    NSString *fullPath = [[NSBundle mainBundle] pathForResource:@"xx" ofType:@"docx"];
    NSData *data = [NSData dataWithContentsOfFile:fullPath];
    

    此外,这一行:

    [body appendData:[NSData dataWithData:data]];
    

    应该只是:

    [body appendData:data];
    

    摆脱对stringWithString:的号召。例如:

    [body appendData:[[NSString stringWithString:@"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
    

    应该是:

    [body appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
    

    NSString *boundary = [NSString stringWithString:@"---------------------------14737809831466499882746641449"];
    

    应该是:

    NSString *boundary = @"---------------------------14737809831466499882746641449";