开发者

Failing to POST NSData of PDF to server

I have an iPad application in which I need to send a server a PDF file, a开发者_JAVA技巧longside two POST variables, a user ID and a job ID. I am using the code below to do this:

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);

The people on the other end of the connection are saying that they are not receiving the PDF file. I have tried all the usual suspects such as trying to find any nil objects.

Would greatly appreciate if anyone could please lend a hand with this!

Thanks. Ricky.


Turns out there was an issue with the boundaries. I needed to add one at the end, after pdfData was added. Thank you for your help.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜