0

学生が最後にドキュメントをアップロードする必要がある登録フォームを作成しようとしています。ただし、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);
}

これを実行しましたが、エラーは発生しませんでした。何も出力されないことを除いて、ファイル名も出力しようとしました。

4

3 に答える 3

0

HTML 要素の値のようにファイルを送信することはできません。ファイルのアップロードには 2 つの方法があります。私が成功した方法は、「AjaxUploader」と呼ばれるサードパーティの機能を使用した AJAX 方法です。ここから GitHub 経由でダウンロードできます。完了したら、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.
    }
}

さらにサポートが必要な場合はお知らせください。PS:うまくいった場合は、回答としてマークすることを忘れないでください。

于 2013-11-05T05:16:56.027 に答える
0

これはあなたのためにそれを行う必要があります:

$("#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";

            }
        });
});

乾杯

于 2013-11-05T05:13:39.687 に答える
0

まず、あなたのコードでは、データを投稿して$.ajax({...})いて、送信されたデータは

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

全くありませんtranscript

第二に、最も重要なことですが$.ajax({...})、そのようなファイルを投稿することはできません。そのようには機能しません。@Roy MJ が言うように、FormData を確認するか (最近のブラウザーのみ)、Web でアップロード jQuery プラグインを確認する必要があります (再発明しないでください。いくつかの優れたプラグインが既に存在します:))

こちらをご覧ください

于 2013-11-05T04:57:32.513 に答える