未能将PDF的NSData发布到服务器

时间:2010-11-27 03:31:01

标签: cocoa-touch nsdata nsurlrequest

我有一个iPad应用程序,我需要向服务器发送一个PDF文件,以及两个POST变量,一个用户ID和一个作业ID。我使用下面的代码执行此操作:

NSData * pdfData = [NSData dataWithContentsOfFile:currentPDFFileName];

    NSData *validPDF = [[NSString stringWithString:@"%PDF"] dataUsingEncoding: NSASCIIStringEncoding];
    if (!(pdfData && [[pdfData subdataWithRange:NSMakeRange(0, 4)] isEqualToData:validPDF])) 
    {
        NSLog (@"Not valid");
    }

    NSLog (@"%@", currentPDFFileName);
    NSLog (@"%@", [currentPDFFileName lastPathComponent]);

    //create the body
    NSMutableData *body = [NSMutableData data];

    //create the POST vars
    NSString *jobID = [NSString stringWithFormat:@"Content-Disposition: form-data; name=\"jobid\"\r\n\r\n%@", job.jobID];
    NSString *userID = [NSString stringWithFormat:@"Content-Disposition: form-data; name=\"userid\"\r\n\r\n%@", delegate.userID];
    NSString *pdf = [NSString stringWithFormat:@"Content-Disposition: form-data; name=\"image_file\"; filename=\"%@\"\r\n", [currentPDFFileName lastPathComponent]];

    [body appendData:[[NSString stringWithFormat:@"--%@\r\n", @"----foo"] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[jobID dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n", @"----foo"] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[userID dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n", @"----foo"] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[pdf dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[@"Content-Type: application/pdf\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:pdfData];

    NSMutableURLRequest *pdfRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://example.com"]];
    [pdfRequest setValue:@"multipart/form-data; boundary=----foo" forHTTPHeaderField:@"Content-type"];
    [pdfRequest setHTTPMethod:@"POST"];
    [pdfRequest setHTTPBody:body];
    NSData *pdfDataReply;
    NSURLResponse *pdfResponse;
    NSError *pdfError;
    pdfDataReply = [NSURLConnection sendSynchronousRequest:pdfRequest returningResponse:&pdfResponse error:&pdfError];

    NSString *pdfResult = [[NSString alloc] initWithData:pdfDataReply encoding:NSASCIIStringEncoding];
    NSLog (@"%@", pdfResult);

连接另一端的人说他们没有收到PDF文件。我已经尝试了所有常见的嫌疑人,例如试图找到任何零物体。

如果有人愿意请帮忙,我将不胜感激!

感谢。 瑞奇。

1 个答案:

答案 0 :(得分:0)

事实证明边界存在问题。在添加pdfData之后,我需要在最后添加一个。谢谢你的帮助。