Michael
Michael

Reputation: 23

How to save 'multipart/form-data' (picture, pdf, and etc.) to mysql database mediumblob via jquery?

I am building an assessment tool. The logic is:

  1. In each question, once I click 'Upload/View Files', it will pop up a modal;

  2. In the modal, there is a section you can select pic/document/video to upload. The code is as: Html code

  3. Once you click submit, it will trigger jquery as below:

    $(document).ready(function(){   
        $('#upload_file_attachment').submit(function(event){
            event.preventDefault();
            var formData = new FormData($(this)[0]);
            $.ajax({
                url: "ajax/upload-attachment.ajax.php",
                type: "POST",
                data: formData,
                async: false,
                cache: false,
                contentType: false, 
                processData: false,
                'success': function(data){
                                $('#upload_success_msg').fadeIn().html(data);
                                setTimeout(function(){
                                    $('#upload_success_msg').fadeOut("Slow");
                                },5000);
                            }
            }); //End of ajax
    
    
    
    })//End of submit
    
    })
  4. And the following is ajax php code:

    require_once '../php-includes/connect.inc.php';
    global $db;
    $assess_id=$_POST['assess_id'];
    $quest_ref=$_POST['quest_ref'];
    $email=$_POST['email'];
    $type=$_POST['type'];
    
    if($type=="file"){
        $file=$_FILES["file"];
        $fileName=$file["name"][0];
        if(empty($fileName)){
            echo "No File Selected";
            return;
        }
        $fileType=$file["type"][0];
        $fileData=$file["tmp_name"][0];
    
    
    mysqli_query($db, "INSERT INTO `files` VALUES('$assess_id','$quest_ref','$fileName','$fileType','$fileData', NOW(), '$email', '')");
    echo "Success";
    
    }
  5. However, when I check database after uploading the file, it only upload the name like 'C:xampp mpphpFE6F.tmp' into the blob, apparently the $fileData is not correct. Could you please help me how i can do this?

Thanks

Upvotes: 2

Views: 1455

Answers (2)

cssyphus
cssyphus

Reputation: 40106

Simplest solution, use this plugin:

http://hayageek.com/docs/jquery-upload-file.php#doc

Ravishanker Kusuma has done such a good job that there is no point rolling your own. (I am not in any way associated with RK, nor have I even communicated with him, but have used this plugin for years.)

Alternatively, you can use his plugin as a learning tool / template and look at his code to see how he did it.

Upvotes: 1

djorborn
djorborn

Reputation: 151

Another way to do it is to save your images to your server or something like cloudinary and save the created link to SQL.

Upvotes: 1

Related Questions