0

我想将本地 word(或 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);
4

1 回答 1

1

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

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

  1. 您需要指定文件的完整路径,而不仅仅是文件名。
  2. 由于您正在从文件路径创建一个NSURL,因此您需要使用fileURLWithPath:,而不是URLWithString:.

编辑:根据您的评论,该文件位于应用程序的资源包中。要获得其完整路径,您应该这样做:

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";
于 2013-07-17T23:30:06.963 回答