refactory-id / bootstrap-markdown

Bootstrap plugin for markdown editing
Apache License 2.0
1.99k stars 371 forks source link

Upload of non-image files #330

Open skylord123 opened 3 years ago

skylord123 commented 3 years ago

Currently if you enable dropdown and drag-n-drop a non-image file it will try to render the file as an image. It would be nice to support any sort of file being uploaded instead of just images.

I was able to get this working by making these modifications to the drop zone success handler:

            options.dropZoneOptions.init = function() {
              var caretPos = 0;
              this.on('drop', function(e) {
                  caretPos = textarea.prop('selectionStart');
                });
              this.on('success', function(file, path) {
                console.log("success", file, path);
                  var url = window.URL || window.webkitURL;
                  var image = new Image();
                  image.onload = function() {
                    var text = textarea.val();
                      textarea.val(text.substring(0, caretPos) + '\n!['+file.name+'](' + path + ')\n' + text.substring(caretPos));
                    url.revokeObjectURL(image.src);
                  };
                  image.onerror = function() {
                    var text = textarea.val();
                      textarea.val(text.substring(0, caretPos) + '\n['+file.name+'](' + path + ')\n' + text.substring(caretPos));
                    url.revokeObjectURL(image.src);
                  };
                  image.src = url.createObjectURL(file);
              });
              this.on('error', function(file, error, xhr) {
                  console.log('Error:', error);
                });
            };

This also isn't dependent on the extension of the file because it tries to render the image using javascript and listens to the events. This works great for me and now non-image files are rendered as links instead.

If we decide to do a PR to merge this in we may want to change the image upload button to a file upload button.