2012-11-15 52 views
1

我正在iPhone应用程序中,通过Web服务从文档目录上传pdf文件,如“http://www.publigeee.com/index.php?q=api/upload & uid = 1 & title =示例&文件=在这里上传Pdf文件“,该怎么做? 请帮帮我。通过iPhone的网络服务上传pdf文件(从文档目录)?

在此先感谢

+2

查找和正确,有一个搜索框 - http://stackoverflow.com/ q uestions/8564833/ios-upload-image-and-text-using-http-post –

+0

感谢您的回复 – SampathKumar

+0

此链接仅用于上传文本,但我希望通过pdf文件进行上传 – SampathKumar

回答

4

前几天我做了这个。该代码使用AFNetworking:https://github.com/AFNetworking/AFNetworking

代码在iPhone上侧(其上载的PDF和其他文本参数项)

NSData *itemData = [NSData dataWithContentsOfFile:filePath]; // filePath is the path of your PDF. This is an NSData containing your pdf file 
NSString *itemValue = @"A Text Item"; // another text item to upload if you need, like a description ecc... 

NSString *uploadURL = @"http://www.baseurl.it/"; // this is your upload url, the main site where you have your php file to receive the data 
NSURL *url = [[NSURL alloc]initWithString:uploadURL]; 
AFHTTPClient *httpClient = [[AFHTTPClient alloc]initWithBaseURL:url]; 
NSDictionary *dict = [NSDictionary 
         dictionaryWithObjects:@[itemValue] 
         forKeys:@[@"item"]]; 

// @"path/to/page.php" is the path to your php page receiving data 
NSURLRequest *request = [httpClient multipartFormRequestWithMethod: @"POST" 
        path:@"path/to/page.php" 
       parameters:dict 
constructingBodyWithBlock: ^(id <AFMultipartFormData> formData) { 
     if (itemData) 
     { 
      [formData appendPartWithFileData:itemData 
             name:@"pdfData" 
            fileName:@"pdfData.pdf" 
            mimeType:@"application/pdf"]; 
     } 
}]; 

// sorry for the formatting here, is a long method using blocks 
AFJSONRequestOperation *json = [AFJSONRequestOperation JSONRequestOperationWithRequest:request 
        success: ^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) { 
          NSLog(@"Upload Success"); 
        } 
        failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) { 
          NSLog(@"Error: %@", error.description); 
        }]; 
[json start]; 

在PHP端:

// file upload 
try { 
    $fileName = $_FILES['pdfData']['name']; 
    $tmpName = $_FILES['pdfData']['tmp_name']; 
    $fileSize = $_FILES['pdfData']['size']; 
    $fileType = $_FILES['pdfData']['type']; 

    $fp  = fopen($tmpName, 'r'); 
    $content = fread($fp, filesize($tmpName)); 
    $content = addslashes($content); 
    fclose($fp); 

    if(!get_magic_quotes_gpc()) 
    { 
     $fileName = addslashes($fileName); 
    } 

} catch (Exception $e) { 
    echo json_encode("Error:".$e); 
} 

// $content contains your pdf and you can save it wherever you want 

不知道,如果是没有错误,因为它已经从更长的源代码中获取,所以我修改了一些代码段,但这是一个很好的开始

+0

感谢您的回复 – SampathKumar

+0

你好你有没有 – SampathKumar

+0

有什么问题吗? :-) – LombaX

相关问题