File upload through a modal using Ajax

前端 未结 1 1331
情深已故
情深已故 2021-01-21 02:22

I want to upload a file through a modal using Ajax. How can I do that?

My modal:

相关标签:
1条回答
  • 2021-01-21 03:05

    You can upload the file using bootstrap modal via ajax like this.

    In your form tag use attribute enctype and form html will be like below:

     <form enctype="multipart/form-data" id="modal_form_id"  method="POST" >
        <input type="file" name="documents">
     </form>
    

    Js code:

        var postData = new FormData($("#modal_form_id")[0]);
    
                             $.ajax({
                                     type:'POST',
                                     url:'your-post-url',
                                     processData: false,
                                     contentType: false,
                                     data : postData,
                                     success:function(data){
                                       console.log("File Uploaded");
                                     }
    
                                  });
    

    On your controller side you can do in the function like below to upload image.

        if(Input::hasFile('documents')) {
    
            $path = "directory where you wish to upload file";
    
            $file_name= Input::file('documents');   
            $original_file_name = $file_name->getClientOriginalName();
    
            $extension       = $file_name->getClientOriginalExtension();
            $fileWithoutExt  = str_replace(".","",basename($original_file_name, $extension));  
            $updated_fileName = $fileWithoutExt."_".rand(0,99).".".$extension; 
    
            $uploaded = $file_name->move($path, $updated_fileName);
    
            echo $updated_fileName;
    
        }
    
    0 讨论(0)
提交回复
热议问题