【问题标题】:PHP can't pick up filePHP 无法获取文件
【发布时间】:2013-11-05 04:30:12
【问题描述】:

我一直在尝试创建一个注册表单,要求学生在最后上传文件。但是,通过 jQuery 获取表单值后,PHP 文档似乎无法获取我上传的表单。有任何想法吗?

表格:

<form id="joinUs"  enctype="multipart/form-data" method="post">
   <!--various form fields-->
    <input type="file" name="transcript" id="transcript">
    <div class="button" id="submit">Submit!</div>
</form>

jQuery:

$("#submit").click(function(){
    //firstName, lastName, grade, studentID, email, phone are all form values
   var data = "firstName="+firstName+"&lastName="+lastName+"&grade="+grade+"&studentID="+studentID+"&email="+email+"&phone="+phone;
         $.ajax({
                            type: "POST",
                            url: "join_submit.php",
                            data: data,
                            success: function() {                                        
                                   location.href="http://mvcsf.com/new/success.php";

                            }
                    });

join_submit.php

  $allowedExtensions = array("pdf");
$max_filesize = 20000;
$upload_path = "docs/transcripts";
$filename = $_FILES["transcript"]["name"];          
$filesize = $_FILES["transcript"]["size"];
$extension = $_FILES["transcript"]["type"];
 if ($_FILES["transcript"]["error"] > 0) {
        echo "Error: " . $_FILES["transcript"]["error"] . "<br />";
    }
else if((in_array($extension, $allowedExtensions)) && ($filesize < $max_filesize)) {
    move_uploaded_file($_FILES["transcript"]["tmp_name"], $upload_path . $filename);
}

我运行了这个,没有出错。我也尝试打印出文件名,除了没有打印出来。

【问题讨论】:

  • 您需要将文件作为 FormData() 传递。否则在另一端获取不到文件
  • 唯一想到的是,您是否使用大于或小于20000 的文件进行了测试?这不是很大,20,000 字节。如果是这样,那么这就是将停止上传的一件事。其次,尝试在$upload_path = "docs/transcripts";末尾添加正斜杠,例如$upload_path = "docs/transcripts/";,并确保该文件夹具有写权限,包括子文件夹。
  • @RoyMJ,谢谢,我会看看!
  • @Fred-ii-,我尝试使用小于 20,000 的文件上传文件。我检查了文件权限,它设置为 777。我会尝试正斜杠。

标签: php jquery file-upload


【解决方案1】:

这应该为你做:

$("#submit").click(function () {

        var transcript = $("#transcript").val();

        var data = "firstName=" + firstName + "&lastName=" + lastName + "&grade=" + grade + "&studentID=" + studentID + "&email=" + email + "&phone=" + phone;
        var formData = new FormData();

        formData.append("file", transcript);
        formData.append("data", data);

        $.ajax({
            type: "POST",
            url: "join_submit.php",
            enctype: 'multipart/form-data',//optional
            cache: false,
            contentType: false,
            processData: false,
            data: {
                file: file
                data: data
            },
            success: function () {
                location.href = "http://mvcsf.com/new/success.php";

            }
        });
});

干杯

【讨论】:

  • 谢谢!我稍后会试试这个并回复你。虽然我有一个问题 - 你在哪里将 formData 传递给 ajax 请求? (我只是想了解它是如何工作的)
  • 不,这基本上只是以特定格式发送出去。步骤formData.append("file", transcript); 执行此操作。在 ajax 中,您将其传递为 data: { file: filename data: data },
  • 对于声明file: filename 的行,那里应该还有其他内容吗?我运行了它,除了表单不再提交
  • 好的,我改了。它应该是被包装在表单数据中的文件字段值...
【解决方案2】:

首先,在您的代码中,您使用$.ajax({...}) 发布数据,发送的数据是

"firstName="+firstName+"&lastName="+lastName+"&grade="+grade+"&studentID="+studentID+"&email="+email+"&phone="+phone;

根本没有transcript

其次,也是最重要的,你不能像这样使用$.ajax({...}) 发布文件,它不会那样工作。正如@Roy M J 所说,你应该看看FormData(仅适用于最近的浏览器),或者在网上查看一个上传jQuery插件(不要重新发明,一些好的插件已经存在:))

看看here

【讨论】:

    【解决方案3】:

    您不能像发送 HTML 元素的值那样发送文件。文件上传有两种方法,我使用成功的一种是使用名为“AjaxUploader”的第三方功能的AJAX方法。您可以通过GitHubdownload it here。完成后,将 ajaxuploader.js 文件添加到您的“js”文件夹(或您放置所有脚本文件的任何位置)中,将该文件包含在您必须使用上传器的 HTML 页面中。现在,上传很简单,如下所示。
    HTML:

    <input type="file" name="transcriptUploader" id="transcriptUploader" value="Upload" />
    

    jQuery(您需要将 jQuery 文件包含在您的页面中):

                new AjaxUpload('transcriptUploader', { 
                action: "page_to_handle_upload.php", // You need to have either a separate PHP page to handle upload or a separate function. Link to either one of them here
                name: 'file',
                onSubmit: function(file, extension) {
                    // This function will execute once a user has submitted the uploaded file. You can use it to display a loader or a message that the file is being uploaded.
                },
                onComplete: function(file, response) {
                    // This function will execute once your file has been uploaded successfully.
                    var data = $.parseJSON(response); // Parsing the returning response from JSON.
                    if(data.error == 0)
                    {
                        // If the file uploaded successfully.
                    }
                    else if(data.error == "size"){
                        // If the response object sent 'size' as the error. It means the file size exceeds the size specified in the code.
                    }
                    else if(data.error == "type"){
                        // If the response object sent 'type' as the error. It means the file type is not of that specified in the code (in your case, pdf).
                    }
                    else{
                        // In case the file didn't upload successfully or the code didn't return a usual error code. It is still an error so you need to deal with it appropriately.
                    }
    
                }
            });
    

    您的后端 PHP 代码将完成所有繁重工作(上传文件、检查扩展名、移动文件等):

    if(isset($_FILES)) // Checking if a file is posted.
    {
        if ($_FILES['file']['error'] == 0) //Checking if file array contain 0 as an error. It means AJAX had no error posting the file.
        {
            $response = array(); // Initializing a new array.
            $allowedExts = array("pdf"); // Allowable file format.
            $filename = stripslashes($_FILES['file']['name']); // Storing file name.
            //$extension = strtolower(self::_getExtension($filename)); // Fetching file extension.
            // Code block to extract file extension and storing it in a variable called $extraction.
            $i = strrpos($str, ".");
            if (!$i)
            {
                $extension = "";
            }
            $l = strlen($str) - $i;
            $extension = strlower(substr($str, $i + 1, $l));
            $size = $_FILES['file']['size']; // Storing file size (in bytes).
            $fileNameAfterUpload =  md5((time() + microtime())) . '.' . $extension; // Concatinating file name and extension.
            $baseSystemPath = "/var/www/<your_folder_name>/uploaded_transcripts/" // Path on which the file will be uploaded. Need to be relative web path.
            $maxSize = 10*10*1024; // Storing file size. Be advised the file size is in bytes, so this calculation means max file size will be 10 MB.
            $webPath =  "uploaded_transcripts/". $filename; // Creating web path by concatinating base web path (the folder in which you'd be uploading the pdf files to) with file name.
    
    
            if (in_array($extension, $allowedExts)) // Checking if file contains allowabale extensions.
            {
                if($size <= $maxSize) // Checking if the size of file is less than and equal to the maximum allowable upload size.
                {
                    $moved = move_uploaded_file($_FILES['file']['tmp_name'], $webPath); // Moving the file to the path specified in $webPath variable.
                    if($moved == true)
                    {
                        $response['error'] = 0; // If moved successfully, storing 0 in the response array.
                        $response['path'] = $webPath; // Storing web path as path in the response array.
                        $response['filename'] = $filename; // Storing file name in the response array.
                    }
                    else 
                 {
                        $response['error'] = 'internal'; // If move isn't successfull, return 'internal' to AJAX.
                    }
                }
                else
                {
                     $response['error'] = 'size'; // If file size is too small or large, return 'size' to AJAX.
                }
            }
            else
            {
                 $response['error'] = 'type'; // If file type is not that of defined, return 'type' to AJAX.
            }
            echo json_encode($response); // Returning the response in JSON format to AJAX.
        }
    }
    

    如果您需要进一步的帮助,请告诉我。 P.S:如果有效,请不要忘记将其标记为答案。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-23
      • 2018-01-24
      相关资源
      最近更新 更多