簡體   English   中英

在iPhone中通過Web服務上傳pdf文件(從文檔目錄)?

[英]Upload pdf file (from document directory) through web service in iPhone?

我正在使用iPhone應用程序,通過Web服務從文檔目錄上傳pdf文件,如“http://www.publigeee.com/index.php?q=api/upload&uid=1&title=Sample&file=Upload Pdf file here”,如何要做到這一點? 請幫我。

提前致謝

我幾天前就做過這個。 此代碼使用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

不確定它是否沒有錯誤,因為它是從更長的源代碼中獲取的,所以我修改了一些代碼,但這是一個好的開始

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM