3

I currently have a working MVC solution which acts as a kind of "IT Helpdesk", I would like to add the functionality of uploading images (easily done by using <input type="file"..../>) however as a lot of people will be copying images from the snipping tool, I am trying to allow them to paste images into the form. This bit works as you can see in the fiddle, however i cannot work out how to then get these images in the controller, if possible at all.

View

<div class="col-sm-12 col-md-12 col-lg-12">
        <label for="fileUploads" class="col-sm-3 col-md-3 col-lg-3">File(s) Upload</label>
        <div name="fileUploads" id="fileUploads" multiple contenteditable="true" style="outline: 1px solid black; overflow: auto;"></div>
</div>

JQuery

document.getElementById("fileUploads").focus();
    document.body.addEventListener("paste", function (e) {
        for (var i = 0; i < e.clipboardData.items.length; i++) {
            if (e.clipboardData.items[i].kind == "file" && e.clipboardData.items[i].type == "image/png") {
                // get the blob
                var imageFile = e.clipboardData.items[i].getAsFile();

                // read the blob as a data URL
                var fileReader = new FileReader();
                fileReader.onloadend = function (e){
                    // create an image
                    var image = document.createElement("IMG");
                    image.src = this.result;

                    // insert the image
                    var range = window.getSelection().getRangeAt(0);
                    range.insertNode(image);
                    range.collapse(false);

                    // set the selection to after the image
                    var selection = window.getSelection();
                    selection.removeAllRanges();
                    selection.addRange(range);
                };

                // TODO: Error Handling!
                // fileReader.onerror = ...

                fileReader.readAsDataURL(imageFile);

                // prevent the default paste action
                e.preventDefault();

                // only paste 1 image at a time
                break;
            }
        }
    });

This is where the JQuery came from

The result of this JQuery inserts an <img> inside of the <div> e.g

<div><img src="...." /> </div>

Community
  • 1
  • 1
hjardine
  • 495
  • 3
  • 17

1 Answers1

0

I suspect the <img> element in the browser contains a base64 encoded image URL right?

Why don't you take the contents of the src attribute and post them back to the server?

Code sample to get you started (in php) here:

How to save a PNG image server-side, from a base64 data string

Community
  • 1
  • 1
Dan
  • 968
  • 1
  • 8
  • 21
  • Thank you, this was perfect (i used a C# version but it put me on the right tracks) [C# version](http://stackoverflow.com/questions/5400173/converting-a-base-64-string-to-an-image-and-saving-it) – hjardine Feb 29 '16 at 10:04