【问题标题】:Post web service to upload pdf file发布网络服务以上传 pdf 文件
【发布时间】:2016-10-20 06:22:33
【问题描述】:

我在 php 中编写了一个脚本,用于从 iOS 应用程序将 pdf 文件上传到服务器,但我不明白为什么它说 undefined index pdfFile 如果你发现我的错误,请告诉我

这是我的 iOS 代码

 Alamofire.upload(
        multipartFormData: { multipartFormData in

          //  multipartFormData.append(pdfUrl!, withName: "pdfFile")

            let pdfData = NSData(contentsOf: pdfUrl!)
            print((pdfData as? Data)!)
            multipartFormData.append((pdfData as? Data)!, withName: "pdfFile", mimeType: "application/pdf")


        },
        to: "http://www.webservice.pixsterstudio.com/uploadpdf.php",
        encodingCompletion: { encodingResult in
            switch encodingResult {
            case .success(let upload, , ):
                upload.responseJSON { response in
                    debugPrint(response)
                    print(response.result)
                }
            case .failure(let encodingError):
                print(encodingError)
            }
        }
    )

这是我的 PHP Web 服务脚本:-uploadpdf.php

  <?php

if ($_FILES['pdfFile']['type'] == "application/pdf") {
    $source_file = $_FILES['pdfFile']['tmp_name'];
    $dest_file = "webservice.pixsterstudio.com/upload/".$_FILES['pdfFile']['name'];

    if (file_exists($dest_file)) {
        print "The file name already exists!!";
    }
    else {
        move_uploaded_file( $source_file, $dest_file )
        or die ("Error!!");
        if($_FILES['pdfFile']['error'] == 0) {
            $Return['status'] = 'true';
            $Return['message'] = "Pdf file uploaded successfully!";
            //print "Pdf file uploaded successfully!";
            //print "<b><u>Details : </u></b><br/>";
            //print "File Name : ".$_FILES['pdfFile']['name']."<br.>"."<br/>";
        //  print "File Size : ".$_FILES['pdfFile']['size']." bytes"."<br/>";
        //  print "File location : upload/".$_FILES['pdfFile']['name']."<br/>";



        }
    }
}
else {
    if ( $_FILES['pdfFile']['type'] != "application/pdf") {
            $Return['status'] = 'false';
            $Return['message'] = "Pdf file not uploaded !";
        //print "Error occured while uploading file : ".$_FILES['pdfFile']['name']."<br/>";
        //print "Invalid  file extension, should be pdf !!"."<br/>";
        //print "Error Code : ".$_FILES['pdfFile']['error']."<br/>";
    }
}
  header('Content-type: application/json');
  echo  json_encode($Return);

 ?>

【问题讨论】:

  • 这是uploadpdf.php的实际代码吗?我看到与空白行相关的错误
  • 是的,这是 uploadpdf.php 的实际代码
  • @Ram Raider 哪里出错了请告诉我
  • 我看到错误报告第 6、31 和 39 行。当我尝试从本地计算机发布 pdf 时收到相同的消息,尽管它显示第 9、34 和 42 行
  • 是同样的错误 undefined pdfFile 对吗?

标签: php ios pdf


【解决方案1】:

在等待咖啡开始时,我很快就写了这篇文章 - 它遵循我通常处理文件上传的方式 - 希望它可能有用。

$fieldname = 'pdfFile';
$targetdir = 'webservice.pixsterstudio.com/upload/';
$desiredtype = 'application/pdf';
$return=array(
    'status'    =>    'false',
    'message'    =>    'Pdf file not uploaded!'
);

if( $_SERVER['REQUEST_METHOD']=='POST' && isset( $_FILES[ $fieldname ] ) ){
    try{

        $obj = (object)$_FILES[ $fieldname ];
        $name = $obj->name;
        $size = $obj->size;
        $tmp  = $obj->tmp_name;
        $type = $obj->type;
        $error= $obj->error;




        if( is_uploaded_file( $tmp ) && $error == UPLOAD_ERR_OK && $type == $desiredtype ){

            $destination = $targetdir . $name;

            if( file_exists( $destination ) ){

                $return['status']='false';
                $return['message']='File already exists!';
                $return['line']=__LINE__;

                clearstatcache();

            } else {

                $res = move_uploaded_file( $tmp, $destination );
                $return['status']=$res ? 'true' : false;
                $return['message']=$res ? 'Pdf file uploaded successfully!' : 'Moving the file failed!';

            }

        } else {
            $return['status']='false';
            $return['message']='File upload error!';
            $return['line']=__LINE__;
        }
    }catch( Exception $e ){
            $return['status']='false';
            $return['message']=$e->getMessage();
            $return['line']=__LINE__;
    }

    header('Content-type: application/json');
    exit( json_encode( $return ) );

} else {
    exit( header( 'HTTP/1.1 405 Method Not Allowed',true, 405 ) );
}

使用下面的表格,我现在收到一条 json 消息,说上传失败...

    <form method='post' action='http://www.webservice.pixsterstudio.com/uploadpdf.php' enctype="multipart/form-data">
        <h1>Upload PDF to WebService</h1>
        <input type='file' name='pdfFile' />
        <input type="submit" value="Send">
    </form> 

{"status":"false","message":"Pdf file not uploaded!"}

【讨论】:

  • Raider 说 405 Method not allowed
  • IOS应用程序是否通过POST发送数据?
  • 是的,我的 iOS 应用程序正在通过 post 方法发送文件
  • 另外,对于基于传统 Web 表单的上传,表单 enctype 必须设置为 multipart/form-data - 也许您需要设置该标题??
  • 我在上面的代码中犯了一个错误 - 我曾尝试将响应写入错误的数组 - 它应该是 $return 数组,但我使用的是 $result... 在本地测试并且它现在似乎可以工作了 - 很抱歉这个错误
【解决方案2】:

让我们检查您的代码您的错误文件 mime 类型。 在php中检查文件类型采取mimetype文件上传。

每个上传文件的 mime 类型都不同

if ($_FILES['pdfFile']['type'] == "pdf") {

}

替换您的 php 文件类型检查行,见上文。 此代码检查每个 pdf mimetype 文件上传。

下面是我的 ios 代码 这是我的代码,我没有收到任何类型的错误。

func callPostWithMultipartService(urlString: String, param : [String: AnyObject]?, fileData : NSData,  completion: (result: String, data : AnyObject) -> Void)
{

    upload(.POST, urlString, multipartFormData: { MultipartFormData in

        MultipartFormData.appendBodyPart(data: fileData, name: "filepdf", fileName: "file.pdf", mimeType: "application/pdf")
        for (key, value) in param! {
            MultipartFormData.appendBodyPart(data: value.dataUsingEncoding(NSUTF8StringEncoding)!, name: key)
        }
        }

【讨论】:

  • 亲爱的 pawan 它没有帮助我...没有改变仍然出现错误未定义索引。
  • @ali saiyad 如果你没有选择文件得到未定义的索引错误,请在上传文件之前检查 isset 条件 (isset($_FILES['pdfFile']) && !empty($_FILES['pdfFile' ])) 和上传文件后。
  • 我试过了,但是 isset 条件不适用于 iOS 我该怎么办?
  • 你会在 php 代码中使用 isset 而不是 ios ode
  • 是的哥们,我尝试在 php 中使用,响应变为空白,没有错误,也没有结果。