Click here to Skip to main content
15,881,741 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi,
What I am trying to do is, when a user pastes an image into my Div, I need the code to automatically post the image back to the server where the code behind can retrieve it. If anyone can help me out it will be GREATLY appreciated!
Thanks
-Doug

What I have tried:

I have spent a few hours on this and have only succeeded in getting the client side code to trigger the Document's onpaste event and capture the data from the clipboard.

The inline code...
<div id="DivPastedImage" contenteditable="true" style="height: 200px; width: 200px; " >
</div>

The Javascript...
document.onpaste = (evt) => {
const dT = evt.clipboardData || window.clipboardData;
const file = dT.files[0];

alert("How do I get the file posted to the code behind?");
}
Posted
Updated 11-Jul-21 23:54pm

1 solution

Use a FormData object to send the file via an AJAX request to the server.
Using FormData Objects - Web APIs | MDN[^]
Using Fetch - Web APIs | MDN[^]
JavaScript
document.onpaste = async (evt) => {
    const dT = evt.clipboardData || window.clipboardData;
    const formData = new FormData();
    for (let i = 0; i < dT.files.length; i++) {
        formData.append("PastedFile", dT.files[i]);
    }
    
    const response = await fetch("path/to/controller/action", {
        method: "POST",
        body: formData
    });
    
    if (!response.ok) {
        // Display error message...
    } else {
        const result = await response.json();
        ...
    }
};
 
Share this answer
 
Comments
[no name] 14-Jul-21 15:21pm    
It works and I learn a couple of things too. Thank you very much!!!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900