在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 =在这里上传Pdf文件,怎么做?
请帮助我。
I'm working in iPhone application, upload pdf file from document directory through Web Service like "http://www.publigeee.com/index.php?q=api/upload&uid=1&title=Sample&file=Upload Pdf file here", How to do that? Please help me.
提前致谢
推荐答案
我几天前就做过这个。此代码使用AFNetworking: https://github.com/AFNetworking/AFNetworking
I've made this just some days ago. This code uses AFNetworking: https://github.com/AFNetworking/AFNetworking
iPhone方面的代码(上传pdf和另一个文本参数,项目)
Code on the iPhone side (it uploads a pdf and another text parameter, item)
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
不确定它是否没有错误,因为它是从较长的来源获取的,所以我修改了一些代码,但这是一个好的开始
Not sure if it's error free, because it has been taken from a longer source, so I've modified some pieces of code, but it's a good start
这篇关于在iPhone中通过Web服务上传pdf文件(从文档目录)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!