Drag n Drop File Upload...javascript settings???

web
mobile

Topic: Drag n Drop File Upload...javascript settings???

luthersites pro premium asked a year ago

I finally got around to adding the Drag and Drop file upload feature to a part of my site. It seems to work as it's supposed to, at least front-end wise.

I am a very text-orientated person and learn from reading and not from watching a video (especially a video where no one is speaking), but I can't find any text-based tutorials on how to configure the javascript (upload path, max-size, file type, etc.).

It's not enough to say "put

$('.file-upload').file_upload();

in your code...", I want to see an example of how to setup the script between the ( and the )!

I can figure it out by looking at the javascript file itself, but a sample/demo would be nice with this, and all of your plugins, especially for those of us who do copy/paste so we don't have to type everything out.


luthersites pro premium answered a year ago

Here's client side setup:1) The field

 <div class="file-upload-wrapper">
 <input type="file" id="blahblah" name="blahblah" class="fileUpload" accept="image/*" data-show-remove="true" data-default-file="someimagefile" />
 </div>

You can set the ID to whatever you want, as well as the name. You could also use the ID for the javascript but this example is using the class "fileUpload" which, again, you can call whatever you want to. The "data-show-remove" attribute isn't necessary as showing it is default. data-default-file adds a nice background image the uploader or you can use it to show what image is currently set in your database.

2) the javascriptFirst - initialize the file_upload and assign to a variable (for the next part):

    var img = $('.fileUpload').file_upload();

the variable can be called whatever you want, but notice the ".fileUpload". This has to be the same as the id or class you use in the file field (see above).

Second - providing for the "Remove" button to function:

           img.on('file_upload.beforeClear', function(event, element){
                return confirm("Are you Sure?");
           });
           img.on('file_upload.afterClear', function(event, element) {
                $.ajax({
                     url: 'path/to/ajax',
                     type: 'POST',
                     data: {
                          'delete_img': 1,
                          'imageid': gotten-through-function-or-other-means
                     }
                })
           })

Since the delete button is enabled pressing it needs to do something. This makes the button throw up a "confirm" alert and if confirmed, it deletes the current image and removes it as the "default-image-file". I have this entire thing inside of another ajax call (for my own purposes) which gets me the image's ID. You can signify which image you're deleting by any means you'd like. Server side looks like this:

if(isset($_POST['delete_img'])) { $pdo->exec("UPDATE table_name SET image_field = NULL WHERE imageid = $_POST[imageid]"); }

Next - adding/uploading the image:

           $(function() {
                $('.fileUpload').change(function() {
                     var fd = new FormData();
                     var file = $('#image_id_being_uploaded')[0].files[0];
                     fd.append('file', file);
                     fd.append('pageid', pid);  //this saves the image's filename to a table
                     fd.append('field', 'field_name_in_database');
                     fd.append('upload_image', 1);  
                     $.ajax({
                          url: 'path/to/ajax',
                          type: 'POST',
                          data: fd,
                          contentType: false,
                          processData: false,
                          success: function(data) {
                               if(data != 0) {
                                    // do something to show good
                               } else {
                                        // do something to show bad, like:
                                    toastr.error("Something went wrong, please try again", "Upload Error");
                               }
                          }
                     })
                })
           })

We create a function which is called if there is a change in the .fileUpload class's field (a drop of a file, for example). We initialize a FormData() which is required for file uploads. We assign a few variables through the .append() function, most importantly the file itself. We then use ajax() to do the upload, being SURE that contentType and processData are both set to false. Create a success function() if you want. I'm really getting into toastr notifications.

Finally the server side for saving the image:

if(isset($_POST['upload_image'])) {
     if(isset($_FILES['file'])) {
          $tempfile = $_FILES['file']['tmp_name'];
          $filename = $_FILES['file']['name'];
          $location = path/to/your/uploads/';         
     }
     $uploadOk = 1;
     $imageFileType = pathinfo($filename, PATHINFO_EXTENSION);
     $valid_extensions = array("jpg", "jpeg", "png");
     if(!in_array(strtolower($imageFileType), $valid_extensions)) {
          $uploadOk = 0;
     }
     $filename = date('Ymdhis'). rand(0,4) .'.'. $imageFileType;

     if($uploadOk == 0) {
          echo 0;
     } else {
          if(move_uploaded_file($tempfile, $location . $filename)) {
               $pdo->exec("UPDATE table_name SET `$_POST[field]` = '$filename' WHERE primary_key = $_POST[pageid]");
          } else {
               echo 0;
          }
     }
}

Pretty straight forward. I limit this particular file upload to images of jpg or png. I also like to randomize filenames, so I create a new filename using the date and time and a random 4 digit string. Totally optional. If the file fails to upload, "0" is returned and in the "success: function()" in ajax you can do something with this.


Anna Morawska staff commented a year ago

Wow, thank you for sharing your implementation with us! Have you considered publishing it as an article on our site? Or would you mind lf we use it somehow in our documentation?


luthersites pro premium commented a year ago

Go ahead and use it as you see fit.


Anna Morawska staff commented a year ago

Ok, thanks again for your contribution :)


luthersites pro premium answered a year ago

Also, to add to this, I do most of my database-type stuff using ajax. I want to be able to upload this file AND save it's path to the database without pressing a button. Again I can figure it out, but it'd be nice if I could actually see it (in a basic sense) how it's done.


Anna Morawska staff answered a year ago

Hi there,

some examples are provided in the package you've downloaded, but I understand your point of view - I'll add it to our todo list, thank you for reporting the issue.

Best, Ania


luthersites pro premium commented a year ago

Yeah I saw those samples, but there's nothing that really shows advanced usage. I'm sure, as it is, I could use a form , but for some ajax applications I don't like using forms. It looks like the plugin is based on dropify, and there is much information on dropify out there. Do I essentially follow the dropify steps but change what needs to be changed for this plugin? BTW this is the only plugin for Bootstrap that, aesthetically, is exactly what I need. It looks great and having the default-image data attribute is perfect for what I'm doing.

But what I want it to do is this:A user drops/selects an image.The image replaces the default-image on the screenThe image is immediately uploaded/sent to the server-side to be processed and savedThe database field where the image filename is stored is also updatedI think I have it figured out but I just want a quick visual example of the client side stuff to make sure it's done right, that's really all.


Anna Morawska staff commented a year ago

Thank you for the detailed explanation - yes, the small example of usage is definitely a good idea, we will work on it. For now, please use the plugin as a regular file input - you can add a custom onChange event, which uploads the image to the server


Please insert min. 20 characters.
Status

Resolved

Specification of the issue
  • User: Pro
  • Premium support: Yes
  • Technology: jQuery
  • MDB Version: 4.7.3
  • Device: PC
  • Browser: Firefox
  • OS: Windows 10
  • Provided sample code: No
  • Provided link: No