the main thing that I am trying to do is get this simple image uploader to also allow the user to enter and store a description along with the image that is uploaded. Also some way to clear the images stored once they are in the preview.
What I currently have is
<html>
<body>
<script type='text/javascript'>
function main()
{
var inputFileToLoad = document.createElement("input");
inputFileToLoad.type = "file";
inputFileToLoad.id = "inputFileToLoad";
document.body.appendChild(inputFileToLoad);
var buttonLoadFile = document.createElement("button");
buttonLoadFile.onclick = loadImageFileAsURL;
buttonLoadFile.textContent = "Load Selected File";
document.body.appendChild(buttonLoadFile);
}
function loadImageFileAsURL()
{
var filesSelected = document.getElementById("inputFileToLoad").files;
if (filesSelected.length > 0)
{
var fileToLoad = filesSelected[0];
if (fileToLoad.type.match("image.*"))
{
var fileReader = new FileReader();
fileReader.onload = function(fileLoadedEvent)
{
var imageLoaded = document.createElement("img");
imageLoaded.src = fileLoadedEvent.target.result;
document.body.appendChild(imageLoaded);
};
fileReader.readAsDataURL(fileToLoad);
}
}
}
main();
</script>
</body>
</html>
Any help you can give would be greatly appreciated!
To get a description just create another input element within the form. Your code is not showing how you actually upload the image. So I guess it's a form with a POST action?
To clear the image, just add a button that removes the "img" element. For ease of use, just make the "imageLoaded" global and then remove that from the DOM when pressing that button.
Related
I'm trying to do a program which is upload and download image.
I write drag and drop function in javascript:
function dragNdrop(event){
var filename = URL.createObjectURL(event.target.files[0]);
var preview = document.getElementById('preview');
var previewImg = document.createElement("img");
previewImg.setAttribute("src",filename);
preview.innerHTML = "";
preview.appendChild(previewImg);
}
function drag(){
document.getElementById('uploadFile').parentNode.className = "draging dragBox";
}
function drop(){
document.getElementById('uploadFile').parentNode.className = 'dragBox';
}
now i want to try download image which is in div tag(preview) in my html. How can i do this?
I've tried to return div image but it have'nt work
Hi I am using native HTML5 drag and drop to upload files to the server. I want to get the name of the file being uploaded from the local system. I am unable to get the name of the file being dropped in the drop zone. Below is the code i have tried. Any help would be appreciated
var reader = new FileReader();
reader.onload = function (event) {
var childrenDivs = document.getElementById("holder").children
var temp
if(childrenDivs.length > 0){
var lastDiv = childrenDivs[childrenDivs.length - 1]
temp = parseInt(lastDiv.id.split("_")[1]) + 1
}else{
temp = 1
}
var imageDiv = document.createElement('div')
imageDiv.id = "uploadedImage_"+temp
var image = new Image();
image.src = event.target.result;
console.log(event.target.fileName)
instead of console.log(event.target.fileName) i have also tried console.log(event.target.files[0].name) and console.log(event.dataTrasfer.files[0]). Could anyone please help me out here.
Where are you calling reader.readAs... method?
AFAIK, the proper place to get the filename would be where you register the drop event of a dom element.
element.ondrop = function(e) {
e.preventDefault();
var reader = new FileReader();
reader.onload = function (event) {
....
}
var file = e.dataTransfer.files[0];
// can get the name of the file with file.name
console.log(file.name);
reader.readAsBinaryString(file);
}
I'm building my own WYSIWYG editor, using an iframe, I'd like to find just a way to simply insert an image! I already got the Bold style, Italic style, H1 and H2, using JS:
function bold(){
editor.document.execCommand("bold", false, null)
}
function italic(){
editor.document.execCommand("italic", false, null)
}
function h1(){
editor.document.execCommand('formatBlock',false,'h1');
}
function h2(){
editor.document.execCommand('formatBlock',false,'h2');
}
That works very well but I'm struggling with "Insert image button"
Since I'm really new with coding, I was trying this:
function image(){
var image = prompt ("Paste or type a link", "http://")
editor.document.execCommand("createImage", false, image)
But that doesn't work. My intention is that the users have the possibility to upload images from their computer and/or from internet. Please, if anyone knows how to insert an image... help!
A LOT OF THANKS IN ADVANCE!
Have you tried formatting your image location using a relative link where the # symbol precedes the image location. Your code and explanation also doesn't explain are they uploading the image from their machine in a location like My Documents or if they are uploading the image strictly from and http link.
To upload from a local machine using Javascript and HTML, you might checkout this code. Your question is one that regularly comes up when writing custom Javascript functions.
<script type='text/javascript'>
function main()
{
var inputFileToLoad = document.createElement("input");
inputFileToLoad.type = "file";
inputFileToLoad.id = "inputFileToLoad";
document.body.appendChild(inputFileToLoad);
var buttonLoadFile = document.createElement("button");
buttonLoadFile.onclick = loadImageFileAsURL;
buttonLoadFile.textContent = "Load Selected File";
document.body.appendChild(buttonLoadFile);
}
function loadImageFileAsURL()
{
var filesSelected = document.getElementById("inputFileToLoad").files;
if (filesSelected.length > 0)
{
var fileToLoad = filesSelected[0];
if (fileToLoad.type.match("image.*"))
{
var fileReader = new FileReader();
fileReader.onload = function(fileLoadedEvent)
{
var imageLoaded = document.createElement("img");
imageLoaded.src = fileLoadedEvent.target.result;
document.body.appendChild(imageLoaded);
};
fileReader.readAsDataURL(fileToLoad);
}
}
}
main();
</script>
You can check out the full article on this issue of image uploads using Javascript and HTML 5 here: https://thiscouldbebetter.wordpress.com/2012/12/20/uploading-and-displaying-an-image-from-a-file-using-html5-and-javascript/
It should be "insertimage" instead of createImage.
function image(){var image = prompt ("Paste or type a link", "http://")editor.document.execCommand("insertimage", false, image)}
you can use this post
var insertImgTag = document.createElement("div");
insertImgTag.id = "insertImgTag";
if (document.getSelection().anchorNode != null) {
document.getSelection().getRangeAt(0).insertNode(insertImgTag);}
$("#insertImgTag")
.parent()
.html(
"<img src=/images/" + $("#name").val() + " width='" + imgWidth + "%' alt='" + imgAlt + "'>"
);
that I used it in my own javascript editor according to this post
I'm creating an app in which I want the user to upload an image with HTML5 <input type="file"/>
I know the browsers restrict getting the path of the image because of security, so i can't copy the image path and put it where ever I want.
Basically I want the user to submit an image, and I want to be able to manipulate the image by setting it as background-image of divs and putting the image in other places. hopefully by changing its source. This is not a server-side app so PHP or any server-side languages aren't an option.
EXAMPLE: If the user clicks a button, the image the user submited can be set as the background-image: url('image-path') of other divs and be applied to to other image tags.
Haven't tested across multiple browsers but can try something like this:
<input type="file" id="file">
$('#file').change(function(evt){
var img = $('<img/>');
var div = $('<div class="with-image"/>');
$(document.body).append(img);
$(document.body).append(div);
var reader = new FileReader();
reader.onload = (function(img) {
return function(ev) {
var image = ev.target.result;
img[0].src = image;
div.css('background-image', 'url("' + image + '")');
};
})(img);
var file = evt.target.files[0];
reader.readAsDataURL(file);
});
Here's a fiddle.
You would want to use the new File API for doing that, and that's really the only way of doing it without a server. Here is an example:
JSFiddle: http://jsfiddle.net/41w6f7n9/
;(function(window, undefined) {
var
doc = window.document,
userFile = doc.getElementById('userFile'),
divPreviews = doc.querySelectorAll('.preview'),
imgPreview = doc.getElementById('img-preview'),
// We will read the file as a Data URL.
fileReader = new FileReader();
var fileutil = {
init: function() {
userFile.addEventListener('change', function(e) {
fileutil.readFile(this.files[0]);
}, false);
},
readFile: function(file) {
var self = this;
// When done reading.
fileReader.onload = function(e) {
if (e.target.readyState === 2) { // 2 means DONE
self.preview(e.target.result);
}
};
// Start reading the file as a Data URL and wait to complete.
fileReader.readAsDataURL(file);
},
preview: function(imageURL) {
imgPreview.src = imageURL;
divPreviews[0].style.backgroundImage = 'url('+imageURL+')';
divPreviews[1].style.backgroundImage = 'url('+imageURL+')';
}
};
fileutil.init();
}(this));
The HTML:
<form>
<input type="file" id="userFile">
</form>
<h1>Image Preview</h1>
<img src="" width="400" id="img-preview">
<h1>Div preview 1</h1>
<div id="preview1" class="preview"></div>
<h1>Div preview 2</h1>
<div id="preview2" class="preview"></div>
I want to upload a temporary text file say '.json' file on front end.
Then view it in a div element of current window html.
say html body has two div
left div have a form with a upload button to upload a file
and right div displays the content of file after uploading the file
I DO NOT WANT TO MAKE ANY REQUEST TO ANY SERVER.
all i want a front end script to upload a file and display within its tab window
Is that possible? How?
<body>
<input id="File" type="file" />
<input id="Button" type="button" value="button" />
<div id="container"></div>
<script>
var input = document.getElementById('File');
var button = document.getElementById('Button');
var container = document.getElementById('container');
button.onclick = function () {
var reader = new FileReader();
reader.onload = function () {
container.innerHTML = reader.result;
}
input.files.length > 0 && reader.readAsText(input.files[0]);
}
</script>
</body>
Demo Fiddle
Javascript
var files = evt.target.files[0];
var reader = new FileReader();
reader.onload = (function () {
return function (e) {
var span = document.createElement('span');
span.innerHTML = e.target.result;
document.getElementById('output').appendChild(span);
};
})(files);
reader.readAsText(files);
References:
1. HTML5Rocks
2. Firefox MDN
Check the browser support for FileApi
Limitation: This code can show only those files which can be readAsText
Here's an example that uses FileReader.readAsBinaryString.
It comes from an app that allows offline modification of images via the canvas element, without using a server. I find that graphics algorithms are much faster to prototype in JS than C/ASM - platform independence and zero compile-time.
Usually, one has to grab an image from a server (either localhost or a remote one) in order to get past the SameOrigin policy.
Error checking is minimal - i.e, you can select a text/video/whatever file and the code will still attempt to load it and set its contents to be the data used to construct a dataURI for an image element.
<!DOCTYPE html>
<html>
<head>
<script>
function byId(e){return document.getElementById(e);}
window.addEventListener('load', onDocLoaded, false);
function onDocLoaded()
{
byId('mFileInput').addEventListener('change', onFileChosen, false);
}
// fileVar is an object as returned by <input type='file'>
// imgElem is an <img> element - can be on/off screen (doesn't need to be added to the DOM)
function loadImgFromFile(fileVar, imgElem)
{
var fileReader = new FileReader();
fileReader.onload = onFileLoaded;
fileReader.readAsBinaryString(fileVar);
function onFileLoaded(fileLoadedEvent)
{
var result,data;
data = fileLoadedEvent.target.result;
result = "data:";
result += fileVar.type;
result += ";base64,";
result += btoa(data);
imgElem.src = result;
imgElem.origType = fileVar.type; // unnecessary for loading the image, used by a current project.
}
}
function onFileChosen(evt)
{
if (this.files.length != 0)
{
var tgtImg = byId('tgt');
var curFile = this.files[0];
loadImgFromFile(curFile, tgtImg);
}
}
</script>
<style>
</style>
</head>
<body>
<input id='mFileInput' type='file'/><br>
<img id='tgt' />
</body>
</html>