I have been trying to upload an image file captured from the clipboard of user to a server (web page implemented through Flask). I have the following code so far (almost verbatim lifted from another Stack Overflow post):
<script type="text/javascript">
// We start by checking if the browser supports the
// Clipboard object. If not, we need to create a
// contenteditable element that catches all pasted data
// Add the paste event listener
console.log("Start");
if (window.addEventListener) {
console.log("new event listener");
window.addEventListener("paste", pasteHandler);
}
else if (window.attachEvent) {
console.log("old event listener");
window.attachEvent("onpaste", pasteHandler);
}
console.log("End");
/* Handle paste events */
function pasteHandler(e) {
console.log("in paste handler");
// We need to check if event.clipboardData is supported (Chrome)
if (e.clipboardData) {
console.log("in clip data");
// Get the items from the clipboard
var items = e.clipboardData.items;
if (items) {
// Loop through all items, looking for any kind of image
for (var i = 0; i < items.length; i++) {
if (items[i].type.indexOf("image") !== -1) {
console.log("image exists in clipboard");
// We need to represent the image as a file,
var blob = items[i].getAsFile();
// and use a URL or webkitURL (whichever is available to the browser)
// to create a temporary URL to the object
var URLObj = window.URL || window.webkitURL;
var source = URLObj.createObjectURL(blob);
var form = document.forms['addbug'];
var fd = new FormData(form);
fd.append('attach',blob);
console.log("image added to form");
}
}
}
}
}
</script>
The part that I am struggling with is saving the captured stream on the server. I am trying to use the following python code to store the file on server:
if form.validate_on_submit():
print('in submit')
if request.method == 'POST':
print('in post')
if 'attach' in request.files:
print('in attach')
upload_file = request.files['attach']
print('upload file = '+str(upload_file))
print(upload_file.filename)
if allowed_file(upload_file.filename):
filename = secure_filename(upload_file.filename)
upload_file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
file_loc = os.path.join(app.config['UPLOAD_FOLDER'], filename)
What I get with the last print statement is:
upload file = <FileStorage: '' ('application/octet-stream')>
which sounds like it is a stream not a file. I think that the upload_file.save does not work as it does not recognize the input as a file, but I have no idea how to (maybe) convert the octet-stream data into a readable file. Or maybe I need to read the blob differently instead of using getAsFile()? Any ideas?