将pdf数据上传到服务器

时间:2013-06-13 11:01:50

标签: iphone ios

我想发送我的pdf文件数据服务器,其中包含一些用户数据,如userId和fileName。

我尝试了2个解决方案,但没有在后端获得pdf文件。即使我在我的文档目录中有pdf文件,它也是成功打开的。

尝试过1:

-(void)uploadDock{
NSString *fileName =[NSString stringWithFormat: @"%@.pdf",@"Inspection"];
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *path = [documentsDirectory stringByAppendingPathComponent:fileName];
    NSData *data=[NSData dataWithContentsOfFile:path];
    NSString *content=[data base64EncodedString];
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];


if ([self.responseData retainCount]) {
    NSLog(@"Do nothing");
    [self.responseData release];
}
self.responseData=[[NSMutableData alloc]init];
NSURL *url = [NSURL URLWithString:@"http://abcgroup.delivery-projects.com:81/api/index.php?keyword=docinsert"];

//self.request = [NSMutableURLRequest requestWithURL:url
//cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];

self.request = [NSMutableURLRequest requestWithURL:url];
NSLog(@"Requst %@",request);
NSString *userid=[userDefaults valueForKey:@"UIDD"];
NSString *title=fileName;
NSString *docname=fileName;
NSString *size=[NSString stringWithFormat:@"%d",[data length]];
NSString *post = [NSString stringWithFormat:@"userid=%@&title=%@&docname=%@&size=%@&content=%@",userid,title,docname,size,content];
NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding];
[self.request setHTTPMethod:@"POST"];

//NSString *POSTBoundary = [NSString stringWithFormat:@"0xKhTmLbOuNdArY"];
//[self.request addValue:[NSString stringWithFormat:@"multipart/form-data; boundary=%@\r\n", POSTBoundary] forHTTPHeaderField:@"Content-Type"];

[self.request setValue:[NSString stringWithFormat:@"%d", postData.length] forHTTPHeaderField:@"Content-Length"];
[self.request setValue:@"application/x-www-form-urlencoded charset=utf-8" forHTTPHeaderField:@"Content-Type"];
[self.request setHTTPBody:postData];
[NSURLConnection connectionWithRequest:self.request delegate:self];
}

尝试2:

我正在从Document目录中读取pdf文件的NSData。 ///// - (无效)uploadDock {

self.condition=3;

NSString *fileName =[NSString stringWithFormat: @"%@.pdf",@"Inspection"];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:fileName];
NSData *data=[NSData dataWithContentsOfFile:path];

NSString *content=[data base64EncodedString];
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];

if ([self.responseData retainCount]) {
    NSLog(@"Do nothing");
}
else{
    self.responseData=[[NSMutableData alloc]init];
}

NSURL *url = [NSURL URLWithString:@"http://abcgroup.delivery-projects.com:81/api/index.php?keyword=docinsert"];
//self.request = [NSMutableURLRequest requestWithURL:url
  //                                     cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
self.request = [NSMutableURLRequest requestWithURL:url];
NSLog(@"Requst %@",request);
NSString *userid=[userDefaults valueForKey:@"UIDD"];
NSString *title=fileName;
NSString *docname=fileName;
NSString *size=[NSString stringWithFormat:@"%d",[data length]];

/*
NSString *post = [NSString stringWithFormat:@"userid=%@&title=%@&docname=%@&size=%@&content=%@",userid,title,docname,size,content];
NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding];
 [self.request setHTTPMethod:@"POST"];

//NSString *POSTBoundary = [NSString stringWithFormat:@"0xKhTmLbOuNdArY"];
//[self.request addValue:[NSString stringWithFormat:@"multipart/form-data; boundary=%@\r\n", POSTBoundary] forHTTPHeaderField:@"Content-Type"];

[self.request setValue:[NSString stringWithFormat:@"%d", postData.length] forHTTPHeaderField:@"Content-Length"];
[self.request setValue:@"application/x-www-form-urlencoded charset=utf-8" forHTTPHeaderField:@"Content-Type"];
[self.request setHTTPBody:postData];
[NSURLConnection connectionWithRequest:self.request delegate:self];
*/

/////
NSMutableURLRequest *request11 = [[NSMutableURLRequest alloc] init] ;
[request11 setURL:url];
[request11 setHTTPMethod:@"POST"];
NSString *boundary = @"---------------------------14737809831466499882746641449";
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
[request11 addValue:contentType forHTTPHeaderField: @"Content-Type"];

NSMutableData *body = [NSMutableData data];
// Pdf File
[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"Content-Disposition: form-data; name=\"content\"; filename=\"INSPECTION.pdf\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
//[body appendData:[@"Content-Disposition: form-data; name=\"content\"\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:data]];
[body appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
//[body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];

[body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"userid\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"%@",userid] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];

[body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"title\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"%@",@"TITLE_TEST1"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];

[body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"docname\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"%@",docname] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];

[body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"size\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"%@",size] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];

[request11 setHTTPBody:body];
[NSURLConnection connectionWithRequest:request11 delegate:self];
//[NSURLConnection sendSynchronousRequest:request11 returningResponse:nil error:nil];

/////
}

6 个答案:

答案 0 :(得分:1)

我使用以下功能上传图像,音频和视频,稍加修改。 在此函数中,urloptions是您要使用userId and fileName等文件发送的查询字符串。

没有机会上传PDF,但希望这会对你有帮助。

-(NSString *)uploadFile:(NSString *)urloptions: (NSString *) ext :(NSData *)imageData{

NSURL *url=[NSURL URLWithString:[NSString stringWithFormat:@"%@&%@",APP_URL,urloptions]];   
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:url];
[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 stringWithFormat:@"Content-Disposition: form-data; name=\"formFile\"; filename=\".%@\"\r\n",ext] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:@"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:imageData]];
[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);
return returnString ;

 //[returnString release];

}

答案 1 :(得分:1)

虽然您可以找到正确发布数据的方法,但使用NSURLConnection周围的包装器(如STHTTPRequest https://github.com/nst/STHTTPRequest)会更加容易和可维护。以下是您的代码的样子:

STHTTPRequest *r = [STHTTPRequest requestWithURLString:@"http://abcgroup.delivery-projects.com:81/api/index.php?keyword=docinsert"];

[r setFileToUpload:@"Inspection.pdf" parameterName:@"myFile"];

[r setPOSTDictionary:@{@"userid":@"", @"title":@"", @"docName":@""}]; // your parameters here

r.completionBlock = ^(NSDictionary *headers, NSString *body) {
    // ...
};

r.errorBlock = ^(NSError *error) {
    // ...
};

[r startAsynchronous];

答案 2 :(得分:0)

要上传任何类型的文件,您可以使用ASIHttpRequest库,您可以从https://github.com/pokeb/asi-http-request.获取

上传文件使用此库的ASIFormDataRequest类,使您的工作变得轻松。

答案 3 :(得分:0)

首先将你的pdf转换成二进制文件

 NSData theData = [NSData dataWithData:[GTMBase64 decodeString:theBinary]]; //first transfer it to NSData.

[m_oTestingWeb loadData:theData
           MIMEType:@"application/pdf"
   textEncodingName:@"UTF-8"
            baseURL:nil];                   //using the web view to show it back

然后将此数据上传到服务器。 您必须在iPhone可以联系的Web服务器上创建API,以便将数据发布到Web服务器。您只需创建一个NSURLConnection即可构建数据包,以便从iPhone应用程序发布数据。

在NSURLConnection中,您可以将其告知POST数据包,然后将数据添加到请求正文中。您的图像数据应转换为UTF8并存储为nvarchar或数据库中这些行的内容。

明白,这是对您必须做的事情的概述,如果不了解您的Web应用程序的内部工作原理,我无法向您详细说明。

答案 4 :(得分:0)

您可以AFNewtork使用最新的资料库: 使用AFNetworking,您可以通过以下方式完成:

NSURL *url = [NSURL URLWithString:@"my_base_url"];
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];
NSData *imageData = UIImageJPEGRepresentation([UIImage imageNamed:@"yourfile.pdf"], 0.5);
NSMutableURLRequest *request = [httpClient multipartFormRequestWithMethod:@"POST" path:@"/upload" parameters:nil constructingBodyWithBlock: ^(id <AFMultipartFormData>formData) {
    [formData appendPartWithFileData:imageData name:@"MainMedia" fileName:@"MainMedia" mimeType:@"image/jpeg"];
}];

AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[operation setUploadProgressBlock:^(NSInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {
    NSLog(@"Sent %lld of %lld bytes", totalBytesWritten, totalBytesExpectedToWrite);
}];

[operation start];

}

下载AFNetworking库并将其添加到您的项目中。

答案 5 :(得分:0)

我可以在“试过2”中找到两个真正的问题

  1. 看来,你忘了最后的分隔符 - 见Irfan DANISH的帖子。
  2. 您需要pdf的二进制文件 - 而不是UTF8。
  3. 此外,不要使用同步请求 - 使用实现委托方法的异步样式。

    并且,您“应该”为pdf部分设置Content-Length标头。