upload image from local into tinyMCE - html

tinyMCE has an insert image button, but how to handle its functionality
pls give some code

I have upvoted the code written by #pavanastechie, but I ended up rewriting it quite a lot. Here's a version that is far shorter, which might have value to some people
tinymce.init({
toolbar : "imageupload",
setup: function(editor) {
var inp = $('<input id="tinymce-uploader" type="file" name="pic" accept="image/*" style="display:none">');
$(editor.getElement()).parent().append(inp);
inp.on("change",function(){
var input = inp.get(0);
var file = input.files[0];
var fr = new FileReader();
fr.onload = function() {
var img = new Image();
img.src = fr.result;
editor.insertContent('<img src="'+img.src+'"/>');
inp.val('');
}
fr.readAsDataURL(file);
});
editor.addButton( 'imageupload', {
text:"IMAGE",
icon: false,
onclick: function(e) {
inp.trigger('click');
}
});
}
});
NOTE: this relies on jquery, and won't work without it. Also, it assumes that the browser supports window.FileReader, and doesn't check for it.

I used pavanastechie's and Chris Lear's solutions, which worked perfectly for me, and wanted to share a complete example built on theirs that uploads the image to the server and embeds the image using the URL provided back by the server:
tinymce.init({
toolbar: 'imageupload',
setup: function(editor) {
initImageUpload(editor);
}
});
function initImageUpload(editor) {
// create input and insert in the DOM
var inp = $('<input id="tinymce-uploader" type="file" name="pic" accept="image/*" style="display:none">');
$(editor.getElement()).parent().append(inp);
// add the image upload button to the editor toolbar
editor.addButton('imageupload', {
text: '',
icon: 'image',
onclick: function(e) { // when toolbar button is clicked, open file select modal
inp.trigger('click');
}
});
// when a file is selected, upload it to the server
inp.on("change", function(e){
uploadFile($(this), editor);
});
}
function uploadFile(inp, editor) {
var input = inp.get(0);
var data = new FormData();
data.append('image[file]', input.files[0]);
$.ajax({
url: '/admin/images',
type: 'POST',
data: data,
processData: false, // Don't process the files
contentType: false, // Set content type to false as jQuery will tell the server its a query string request
success: function(data, textStatus, jqXHR) {
editor.insertContent('<img class="content-img" src="' + data.url + '"/>');
},
error: function(jqXHR, textStatus, errorThrown) {
if(jqXHR.responseText) {
errors = JSON.parse(jqXHR.responseText).errors
alert('Error uploading image: ' + errors.join(", ") + '. Make sure the file is an image and has extension jpg/jpeg/png.');
}
}
});
}

!!!!ENJOY!!! here is the solution to load directly from local computer
JSFIDDLE DEMO
<textarea name="content"></textarea>
<title>Local image loading in to tinymce</title>
<br/>
<b>Image size should be lessthan 500kb</b>
JAVA SCRIPT CODE
`
tinymce.init({
selector: "textarea",
toolbar: "mybutton",
setup: function(editor) {
editor.addButton('mybutton', {
text:"IMAGE",
icon: false,
onclick: function(e) {
console.log($(e.target));
if($(e.target).prop("tagName") == 'BUTTON'){
console.log($(e.target).parent().parent().find('input').attr('id'));
if($(e.target).parent().parent().find('input').attr('id') != 'tinymce-uploader') {
$(e.target).parent().parent().append('<input id="tinymce-uploader" type="file" name="pic" accept="image/*" style="display:none">');
}
$('#tinymce-uploader').trigger('click');
$('#tinymce-uploader').change(function(){
var input, file, fr, img;
if (typeof window.FileReader !== 'function') {
write("The file API isn't supported on this browser yet.");
return;
}
input = document.getElementById('tinymce-uploader');
if (!input) {
write("Um, couldn't find the imgfile element.");
} else if (!input.files) {
write("This browser doesn't seem to support the `files` property of file inputs.");
} else if (!input.files[0]) {
write("Please select a file before clicking 'Load'");
} else {
file = input.files[0];
fr = new FileReader();
fr.onload = createImage;
fr.readAsDataURL(file);
}
function createImage() {
img = new Image();
img.src = fr.result;
editor.insertContent('<img src="'+img.src+'"/>');
}
});
}
if($(e.target).prop("tagName") == 'DIV'){
if($(e.target).parent().find('input').attr('id') != 'tinymce-uploader') {
console.log($(e.target).parent().find('input').attr('id'));
$(e.target).parent().append('<input id="tinymce-uploader" type="file" name="pic" accept="image/*" style="display:none">');
}
$('#tinymce-uploader').trigger('click');
$('#tinymce-uploader').change(function(){
var input, file, fr, img;
if (typeof window.FileReader !== 'function') {
write("The file API isn't supported on this browser yet.");
return;
}
input = document.getElementById('tinymce-uploader');
if (!input) {
write("Um, couldn't find the imgfile element.");
} else if (!input.files) {
write("This browser doesn't seem to support the `files` property of file inputs.");
} else if (!input.files[0]) {
write("Please select a file before clicking 'Load'");
} else {
file = input.files[0];
fr = new FileReader();
fr.onload = createImage;
fr.readAsDataURL(file);
}
function createImage() {
img = new Image();
img.src = fr.result;
editor.insertContent('<img src="'+img.src+'"/>');
}
});
}
if($(e.target).prop("tagName") == 'I'){
console.log($(e.target).parent().parent().parent().find('input').attr('id')); if($(e.target).parent().parent().parent().find('input').attr('id') != 'tinymce-uploader') { $(e.target).parent().parent().parent().append('<input id="tinymce-uploader" type="file" name="pic" accept="image/*" style="display:none">');
}
$('#tinymce-uploader').trigger('click');
$('#tinymce-uploader').change(function(){
var input, file, fr, img;
if (typeof window.FileReader !== 'function') {
write("The file API isn't supported on this browser yet.");
return;
}
input = document.getElementById('tinymce-uploader');
if (!input) {
write("Um, couldn't find the imgfile element.");
} else if (!input.files) {
write("This browser doesn't seem to support the `files` property of file inputs.");
} else if (!input.files[0]) {
write("Please select a file before clicking 'Load'");
} else {
file = input.files[0];
fr = new FileReader();
fr.onload = createImage;
fr.readAsDataURL(file);
}
function createImage() {
img = new Image();
img.src = fr.result;
editor.insertContent('<img src="'+img.src+'"/>');
}
});
}
}
});
}
});
`

Din't try iManager but found tinyFCK good and easy to configure which gives CKEditor's filemanager integrated with TinyMCE
1.Download TinyFCK
2.replace filemanger folder in tinyFCK with filemanager folder of ur CKEditor
3.code :
-
tinyMCE.init({
theme : "advanced",
file_browser_callback : "fileBrowserCallBack",
});
function fileBrowserCallBack(field_name, url, type, win) {
var connector = "../../filemanager/browser.html?Connector=connectors/php/connector.php";
var enableAutoTypeSelection = true;
var cType;
tinyfck_field = field_name;
tinyfck = win;
switch (type) {
case "image":
cType = "Image";
break;
case "flash":
cType = "Flash";
break;
case "file":
cType = "File";
break;
}
if (enableAutoTypeSelection && cType) {
connector += "?Type=" + cType;
}
window.open(connector, "tinyfck", "modal,width=600,height=400");
}

I know this post is old, but maybe this will help someone trying to find a open source file manager for tinymce:
https://github.com/2b3ez/FileManager4TinyMCE
This worked great for me.

Based on #Chris Lear's answer, I have re-modified the script so that it supports multiple file uploads to server, and removed the data image for preview after content is posted and before table is updated with a little php script
tinymce.init({
selector: 'textarea',
setup: function(editor) {
var n = 0;
var form = $('#form_id'); // your form id
editor.addButton( 'imageupload', {
text:"IMAGE",
icon: false,
onclick: function(e) {
$(form).append('<input id="tinymce-uploader_'+n+'" class="tinymce-uploader" type="file" name="pic['+n+']" mutliple accept="image/*" style="display: none;">');
$('#tinymce-uploader_'+n).trigger('click');
n++;
$('.tinymce-uploader').on("change",function(){
var input = $(this).get(0);
var file = input.files[0];
var filename = file.name;
var fr = new FileReader();
fr.onload = function() {
var img = new Image();
img.src = fr.result;
editor.insertContent('<img data-name="'+filename+'" src="'+img.src+'"/>');
}
fr.readAsDataURL(file);
});
}
});
},
And on php side inside the upload php file:
function data2src($content, $img_path ='') {
preg_match('/data\-name="([^"]+)/i',$content, $data_name);
$tmp = preg_replace('/src=["]data([^"]+)["]/i', '', $content);
$content = preg_replace('/data\-name\=\"/i', 'src="'.$img_path, $tmp);
return $content;
}

I know it is an old question. However, I think this answer may help somebody who wants to upload multiple images by using tinyMCE 5.xx.
Based on #Chris Lear's and #stephen.hanson's answer, I modify some code to support multiple images uploading. Here is my code. Hope it could help somebody.
tinymce.init({
toolbar: 'imageupload',
setup: function(editor) {
initImageUpload(editor);
}
});
function initImageUpload(editor) {
// create input and insert in the DOM
var inp = $(`<input id='tinymce-uploader' type='file' name='pic' accept='image/*' style='display:none' multiple>`);
$(editor.getElement()).parent().append(inp);
// add the image upload button to the editor toolbar
editor.addButton('imageupload', {
text:'IMAGE',
onAction: function(_) {
// when toolbar button is clicked, open file select modal
inp.trigger('click');
}
});
// when a file is selected, upload it to the server
inp.on('change',function(){
for(let i=0;i<inp[0].files.length;i++){
let file = inp[0].files[i];
let data = new FormData();
data.append('multipartFile',file);
axios.post('/upload/image/url',
data,
{
headers: {
'Content-Type': 'multipart/form-data'
}
}).then(res => {
if (res.status = 200) {
editor.insertContent('<img class="content-img" src="' + data.url + '"/>');
// clear data to avoid uploading same data not working in the second time
inp.val('');
}
})
}

It works for image upload.Is this possible for file upload ? I want to add a custom file upload option from local into tinyMCE and want to show it by url .
Code is something like below which not working:
ed.addButton('mybutton2', {
text:"File",
icon: false,
onclick: function(e) {
console.log($(e.target));
if($(e.target).prop("tagName") == 'BUTTON'){
console.log($(e.target).parent().parent().find('input').attr('id'));
if($(e.target).parent().parent().find('input').attr('id') !=
'tinymce-uploader') {
$(e.target).parent().parent().append('<input id="tinymce-
uploader" type="file" name="pic" accept="*" height="100" weidth="100"
style="display:none">');
}
$('#tinymce-uploader').trigger('click');
$('#tinymce-uploader').change(function(){
var input, file, fr, img;
if (typeof window.FileReader !== 'function') {
write("The file API isn't supported on this browser yet.");
return;
}
input = document.getElementById('tinymce-uploader');
// var URL = document.my_form.my_field.value;
alert(input.files[0]);
if (!input) {
write("Um, couldn't find the imgfile element.");
} else if (!input.files) {
write("This browser doesn't seem to support the `files`
property of file inputs.");
} else if (!input.files[0]) {
write("Please select a file before clicking 'Load'");
alert( input.files[0]);
} else {
file = input.files[0];
fr = new FileReader();
fr.onload = createFile;
fr.readAsDataURL(file);
// alert(fr.result);
}
function createFile() {
//what should I write here?
ed.insertContent('<a href="'+img.src+'">download
file_name</a>');
}
});
}
}
});

Related

canvas is throw error of tainted after LoadFromJson

I am using fabric js version 1.7.22
when image set in a repetitive manner in a rectangle of fabric js, at
the first time it will be loaded and saved into JSON using toJSON()
and save an image using todataUrl() method, but when cal canvas a loadFromJson method at that time, this canvas not savable, because it throws tainted canvas error.
Please help me,
I already set crossOrigin in a pattern but it not working. and not
added in canvas JSON.
I have made one Fiddle For Generate Issue :
[http://jsfiddle.net/Mark_1998/kt387vLc/1/][1]
Steps to generate issue :
click on 'set pattern'
then click on 'save canvas'
then click on 'reload canvas' // load canvas from JSON
then click on 'save canvas' // cause issue of tainted canvas
This issue is fixed in new version of fabricjs already. If you are still using 1.7.20 the override fabric.Pattern.prototype.toObject and fabric.Pattern.prototype.initialize, find code in snippet.
var canvas = new fabric.Canvas('canvas', {
height: 500,
width: 500,
});
canvas.backgroundColor = '#ff0000';
canvas.renderAll();
var canvasJSON = {};
document.getElementById('setPat').addEventListener('click', function() {
fabric.util.loadImage('https://cdn.dribbble.com/assets/icon-backtotop-1b04df73090f6b0f3192a3b71874ca3b3cc19dff16adc6cf365cd0c75897f6c0.png', function(image) {
var pattern = new fabric.Pattern({
source: image,
repeat: 'repeat',
crossOrigin: 'Anonymous'
});
var patternObject = new fabric.Rect({
left: 0,
top: 0,
height: canvas.height,
width: canvas.width,
angle: 0,
fill: pattern,
objectCaching: false
})
canvas.add(patternObject);
}, null, {
crossOrigin: 'Anonymous'
});
})
document.getElementById('saveCanvas').addEventListener('click', function() {
console.log('save canvas');
canvasJSON = canvas.toJSON();
var image = canvas.toDataURL("image/png", {
crossOrigin: 'Anonymous'
}); // don't remove this, i need it as thumbnail.
//console.log('canvas.Json', canvasJSON);
//console.log('image', image);
canvas.clear();
canvas.backgroundColor = '#ff0000';
canvas.renderAll();
});
document.getElementById('reloadCanvas').addEventListener('click', function() {
console.log('save canvas');
canvas.loadFromJSON(canvasJSON, function() {
canvas.set({
crossOrigin: 'Anonymous'
})
});
console.log('canvas.Json', canvasJSON);
});
//cross origin was not added in toObject JSON
fabric.Pattern.prototype.toObject = (function(toObject) {
return function() {
return fabric.util.object.extend(toObject.call(this), {
crossOrigin: this.crossOrigin,
patternTransform: this.patternTransform ? this.patternTransform.concat() : null
});
};
})(fabric.Pattern.prototype.toObject);
//cross origin was not added while creating image
fabric.Pattern.prototype.initialize = function(options, callback) {
options || (options = {});
this.id = fabric.Object.__uid++;
this.setOptions(options);
if (!options.source || (options.source && typeof options.source !== 'string')) {
callback && callback(this);
return;
}
// function string
if (typeof fabric.util.getFunctionBody(options.source) !== 'undefined') {
this.source = new Function(fabric.util.getFunctionBody(options.source));
callback && callback(this);
} else {
// img src string
var _this = this;
this.source = fabric.util.createImage();
fabric.util.loadImage(options.source, function(img) {
_this.source = img;
callback && callback(_this);
}, null, this.crossOrigin);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.7.20/fabric.js"></script>
<button id="setPat">
Set pattern
</button>
<button id="saveCanvas">
Save canvas
</button>
<button id="reloadCanvas">
Reload CAnvas
</button>
<canvas id="canvas"></canvas>

Upload any text file and preview using only HTML5 and AngularJS

How to upload document of any type like .txt, jpeg or gif and get preview in html page? Only by using HTML5 and AngularJS. No need to save document at any location.
You can use the FileReader API to read the data in the file.
This example modifies the above linked answer and checks if the file type is an image and displays it as such. Otherwise, it displays the file's data as text.
angular.module('fileLoad', []).directive('fileSelect', ['$window', function($window) {
return {
restrict: 'A',
require: 'ngModel',
link: function($scope, el, attr, ctrl) {
var fileReader = new $window.FileReader();
var fileType;
fileReader.onload = function() {
var fileData = {};
fileData.type = fileType;
fileData.data = fileReader.result;
ctrl.$setViewValue(fileData);
$scope.$apply();
};
el.bind('change', function(e) {
var fileName = e.target.files[0];
fileType = (fileName && fileName.type) || '';
if (fileType.indexOf('image') != -1) {
fileReader.readAsDataURL(fileName);
} else if(fileName) {
fileReader.readAsText(fileName);
} else {
ctrl.$setViewValue({});
$scope.$apply();
}
});
}
};
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="fileLoad">
<input type="file" ng-model="file.data" file-select>
<img ng-show="file.data.type && file.data.type.indexOf('image') != -1" data-ng-src="{{file.data.data}}" />
<p ng-show="file.data.type && file.data.type.indexOf('image') == -1" ng-bind="file.data.data"></p>
</div>

In chrome App, video file is not saved with its original data/size

In appCtrl.js, for saving video file -
$('#save_file').click(function(e) {
var config = {type: 'saveFile', suggestedName: chosenEntry.name};
chrome.fileSystem.chooseEntry(config, function(writableEntry) {
//blob content is the DataUrl
var blob = new Blob([$scope.blobContent], {type: 'video/mp4'});
$scope.writeFileEntry(writableEntry, blob, function(e) {
console.log('Write complete :)');
});
});
});
$scope.writeFileEntry = function(writableEntry, opt_blob, callback) {
if (!writableEntry) {
console.log('Nothing selected.');
return;
}
writableEntry.createWriter(function(writer) {
writer.onerror = $scope.errorHandler;
writer.onwriteend = callback;
// If we have data, write it to the file. Otherwise, just use the file we
// loaded.
if (opt_blob) {
writer.truncate(opt_blob.size);
$scope.waitForIO(writer, function() {
writer.seek(0);
writer.write(opt_blob);
});
}
else {
chosenEntry.file(function(file) {
writer.truncate(file.fileSize);
waitForIO(writer, function() {
writer.seek(0);
writer.write(file);
});
});
}
}, $scope.errorHandler);
}
$scope.waitForIO = function(writer, callback) {
// set a watchdog to avoid eventual locking:
var start = Date.now();
// wait for a few seconds
var reentrant = function() {
if (writer.readyState===writer.WRITING && Date.now()-start<4000) {
setTimeout(reentrant, 100);
return;
}
if (writer.readyState===writer.WRITING) {
console.error("Write operation taking too long, aborting!"+
" (current writer readyState is "+writer.readyState+")");
writer.abort();
}
else {
callback();
}
};
setTimeout(reentrant, 100);
};
In above code the video file is saved but when i tried to play that saved file in Window Media Player or VLC player , it prompt me as Window media player cannot play the file.The player might not support the file type or might not support the codec that was used to compress the file.
Can u please guide me where m getting wrong, as its my first chrome app.
Thanks in advance.
Change the method to store blob like this.
function dataURItoBlob(dataURI, callback) {
// convert base64 to raw binary data held in a string
// doesn't handle URLEncoded DataURIs
var byteString = atob(dataURI.split(',')[1]);
// separate out the mime component
var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0]
// write the bytes of the string to an ArrayBuffer
var ab = new ArrayBuffer(byteString.length);
var ia = new Uint8Array(ab);
for (var i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
return new Blob([ab], {type: 'video/mp4'});
};
To handle click.
$('#save_file').click(function(e) {
var config = {type: 'saveFile', suggestedName: chosenEntry.name};
chrome.fileSystem.chooseEntry(config, function(writableEntry) {
var blob = dataURItoBlob($scope.blobContent);
$scope.writeFileEntry(writableEntry, blob, function(e) {
console.log('Write complete :)');
});
});
});

How to add Google Drive Picker in Google web app

what I'm trying to do is to show the Google Picker in my Google Web app. I already tried many ways to accomplish that, but nothing works.
At the moment my code looks like this:
WebApp.html
<!-- rest of the code -->
<button type="button" id="pick">Pick File</button>
</div>
<script>
function initPicker() {
var picker = new FilePicker({
apiKey: "####################",
clientId: "##########-##########################",
buttonEl: document.getElementById('pick'),
onSelect: function(file) {
alert('Selected ' + file.title);
} // onSelect
}); // var picker
} // function initPicker()
</script>
<!-- rest of the code -->
WebAppJS.html
/* rest of the code */
var FilePicker = window.FilePicker = function(options) {
this.apiKey = options.apiKey;
this.clientId = options.clientId;
this.buttonEl = options.buttonEl;
this.onSelect = options.onSelect;
this.buttonEl.addEventListener('click', this.open.bind(this));
this.buttonEl.disabled = true;
gapi.client.setApiKey(this.apiKey);
gapi.client.load('drive', 'v2', this._driveApiLoaded.bind(this));
google.load('picker', '1', { callback: this._pickerApiLoaded.bind(this) });
}
FilePicker.prototype = {
open: function() {
var token = gapi.auth.getToken();
if (token) {
this._showPicker();
} else {
this._doAuth(false, function() { this._showPicker(); }.bind(this));
}
},
_showPicker: function() {
var accessToken = gapi.auth.getToken().access_token;
this.picker = new google.picker.PickerBuilder().
addView(google.picker.ViewId.DOCUMENTS).
setAppId(this.clientId).
setOAuthToken(accessToken).
setCallback(this._pickerCallback.bind(this)).
build().
setVisible(true);
},
_pickerCallback: function(data) {
if (data[google.picker.Response.ACTION] == google.picker.Action.PICKED) {
var file = data[google.picker.Response.DOCUMENTS][0],
id = file[google.picker.Document.ID],
request = gapi.client.drive.files.get({ fileId: id });
request.execute(this._fileGetCallback.bind(this));
}
},
_fileGetCallback: function(file) {
if (this.onSelect) {
this.onSelect(file);
}
},
_pickerApiLoaded: function() {
this.buttonEl.disabled = false;
},
_driveApiLoaded: function() {
this._doAuth(true);
},
_doAuth: function(immediate1, callback) {
gapi.auth.authorize({
client_id: this.clientId + '.apps.googleusercontent.com',
scope: 'https://www.googleapis.com/auth/drive.readonly',
immediate: immediate1
}, callback);
}
}; // FilePicker.prototype
/* rest of the code */
For now, what this code does is showing kind of a popup, but empty. Code is based on Daniel15's code.
What I already tried is:
relocating chunks of code, to server-side and client-side,
using htmlOutput, htmlTemplate - non of those works,
many other things, that i can't exactly remember.
What I would like to get is answer to the question: Why this code doesn't show Google Picker.
Thanks in advance.
Try adding a call origin and developer key
_showPicker: function() {
var accessToken = gapi.auth.getToken().access_token;
this.picker = new google.picker.PickerBuilder()
.addView(google.picker.ViewId.DOCUMENTS)
.setAppId(this.clientId)
.setOAuthToken(accessToken)
.setCallback(this._pickerCallback.bind(this))
.setOrigin('https://script.google.com') //
.setDeveloperKey(BROWSERKEYCREATEDINAPICONSOLE) //
.build()
.setVisible(true);
},

Display image with requestFileSystem and toUrl() function

I made an application who use requestFileSystem. Everything works fine.
Add a new image and store it in an persistent local file system.
Does anybody know how to display an image with toUrl() ?
...
window.requestFileSystem(window.PERSISTENT, 5*1024*1024, function(fs){
fs.root.getDirectory(itemId, {create: false}, function(dirEntry) {
var dirReader = dirEntry.createReader();
var entries = [];
var readEntries = function() {
dirReader.readEntries (function(results) {
if (!results.length) {
listResults(entries.sort(), itemId);
} else {
entries = entries.concat(fsdatas.dir.toArray(results));
readEntries();
}
}, errorHandler);
};
readEntries();
});
}, errorHandler);
...
And
function listResults(entries, itemId) {
document.querySelector('#listRecordFiles-'+itemId).innerHTML = '';
var fragment = document.createDocumentFragment();
var i = 0;
entries.forEach(function(entry, i) {
i++;
var img = document.createElement('img');
img.src = entry.toURL();
fragment.appendChild(img);
});
document.querySelector('#listRecordFiles-'+itemId).appendChild(fragment);
}
The output is :
<img src="filesystem:http://domain.tld/persistent/1/image-test.jpg">
But nothing is displayed on browser.
The example below is a snippet of code responsible for reading the images saved in the application's root directory, and show in the document body.
Remember, in this case, I used navigator.camera.DestinationType.DATA_URL to open the PHOTOLIBRARY, and saved the image content using atob (ascii to binary), so carry the image with btoa (binary to ascii)
function myLoadFile(filename) {
var myDocument = document.querySelector("body");
filesystem.root.getFile(filename, {}, function(fileEntry) {
fileEntry.file(function(file) {
var reader = new FileReader();
reader.onload = function(e) {
var img = document.createElement('img');
// if you save the file with atob (ascii to binary), then:
img.src = "data:image/jpeg;base64,"+btoa(this.result);
// if you don't save the file without atob, then:
// img.src = "data:image/jpeg;base64,"+this.result;
myDocument.appendChild(img)
};
reader.readAsText(file);
}, errorHandler);
}, errorHandler);
}