Download an image from an html input - javascript

I've a problem with my website. I want when an user add an image from
this input :
`input type="file" class="form-control-file" id="Image" name="Image">`
I want to automatically download this image. I would prefer to download from front end. I try in JavaScript but not working.... Does anyone have an idea please ?
I despair.
Anatole
Edit : I want to download the image in my website folder ^^

you can add onchange listener that track input change
user input
<input oninput="onclickhandler(this)"></input>
script
<script>
function download(filename, url) {
var element = document.createElement('a');
element.setAttribute('href', url);
element.setAttribute('download', filename);
document.body.appendChild(element);
element.click();
//remove the hidden link
//document.body.removeChild(element);
}
function onclickhandler(e) {
var name = e.files[0].name;
var file = e.files[0];
var blob = new Blob([file]);
var url = URL.createObjectURL(blob);
download(name,url);
}
</script>

Related

I want to extract a string from a text file and output it as a text file again

I want to extract a string from a text file, convert it to a word scrambler (I figured out that part) and output it in another text file.
I found some code to input a text file and extract the text:
<html>
<h4>Select un file con .txt extension</h4>
<input type="file" id="myFile" accept=".txt" />
<br /><br />
<div id="output"></div>
<script>
var input = document.getElementById("myFile");
var output = document.getElementById("output");
input.addEventListener("change", function () {
if (this.files && this.files[0]) {
var myFile = this.files[0];
var reader = new FileReader();
reader.addEventListener("load", function (e) {
output.textContent = e.target.result;
});
reader.readAsText(myFile);
}
});
</script>
</html>
Input text and extract a text file
<html>
<div>
<input type="text" id="txt" placeholder="Write Here" />
</div>
<div>
<input type="button"id="bt"value="Save in a File"onclick="saveFile()"/>
</div>
<script>
let saveFile = () => {
const testo = document.getElementById("txt");
let data = testo.value;
const textToBLOB = new Blob([data], { type: "text/plain" });
const sFileName = "Testo.txt";
let newLink = document.createElement("a");
newLink.download = sFileName;
newLink.href = window.URL.createObjectURL(textToBLOB);
newLink.style.display = "none";
document.body.appendChild(newLink);
newLink.click();
};
</script>
</html>
But I don't know how to output a string in the first code or how to connect it to the second code. Could someone please show me how to do it or explain how these codes work so that I could try to do it myself in JavaScript?
I will comment each line of JavaScript, that should help you understand.
<script>
/*This creates a global variable with the HTML element input in it. */
var input = document.getElementById("myFile");
/*This creates a global variable with the HTML element div with id output in it. */
var output = document.getElementById("output");
/* this 2 lines are used to set the source and the destination.
The first will get where you put your file, in this case it's the input element.
The second will get the div which content will be replaced by the content of your txt file. */
/* Here we tell to our input element to do something special when his value changes.
A change will occur for example when a user will chose a file.*/
input.addEventListener("change", function () {
/* First thing we do is checking if this.files exists and this.files[0] aswell.
they might not exist if the change is going from a file (hello.txt) to no file at all */
if (this.files && this.files[0]) {
/* Since we can chose more than one file by shift clicking multiple files, here we ensure that we only take the first one set. */
var myFile = this.files[0];
/* FileReader is the Object in the JavaScript standard that has the capabilities to read and get informations about files (content, size, creation date, etc) */
var reader = new FileReader();
/* Here we give the instruction for the FileReader we created, we tell it that when it loads, it should do some stuff. The load event is fired when the FileReader reads a file. In our case this hasn't happened yet, but as soon as it will this function will fire. */
reader.addEventListener("load", function (e) {
/* What we do here is take the result of the fileReader and put it inside our output div to display it to the users. This is where you could do your scrambling and maybe save the result in a variable ? */
output.textContent = e.target.result;
});
/* This is where we tell the FileReader to open and get the content of the file. This will fire the load event and get the function above to execute its code. */
reader.readAsText(myFile);
}
});
</script>
With this I hope you'll be able to understand the first part of this code. Try putting the second part of your code instead of output.textContent and replacing data with e.target.result, that should do what you wish, but I'll let you figure it out by yourself first, comment on this answer if you need further help !
Here's a codepen with working and commented code:
https://codepen.io/MattDirty/pen/eYZVWyK

Download a file from a link on button value

I searched a lot but couldn't find a solution I thank anyone who can help me.
I want to download files on button click but based on values in the text of buttons.
I have three buttons in my HTML like this
<input type="button" onclick="myFunction(this, name1.mp3)" value="button1.mp3">
<input type="button" onclick="myFunction(this, name2.mp3)" value="button2.mp3">
<input type="button" onclick="myFunction(this, name3.mp3)" value="button3.mp3">
my JavaScript is
function myFunction(elmnt, name) {
var url = "http://mysite*com/" + elmnt.value;
var downloadFileWithThisName = name;
---my download code---
}
How can I download my url with the name I passed to function?
what should I write for ---my download code--- part?
Thank you in advance.
function myFunction(elmnt, name) {
var url = "http://mysite*com/" + elmnt.value;
const a = document.createElement('a');
a.href = url;
a.download = name; // here you can specify your filename
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
window.URL.revokeObjectURL(url);
}
What you could do is to dynamically create an A element, add the 'download' attribute, set the Href and click it, all in code. Then remove it from the DOM.
The best answer judging for your code is shown here: https://stackoverflow.com/a/42696866/1891140
var file_path = 'host/path/file.ext';
var a = document.createElement('A');
a.href = file_path;
a.download = file_path.substr(file_path.lastIndexOf('/') + 1);
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
But you also can do it by using a simple JQUERY:
$("<a href='"+url+"' download class='hidden-a'></a>").appendTo("body");
$(".hidden-a")[0].click();

Create a Pop up window where user can choose name when saving file

I have a code where users can save a txt file. In the function I'm using this.title + 'txt', but by request users want to be able to write/choose a name of the file.
For this I was thinking a Pop up box with an input text field, somewhere inside the function without changing existing html. That's means I just want to do it when calling the function.
Can it be done?
The button in the html page
<button _ngcontent-c1="" class="btn btn-success">Spara insats och odds</button>
In download.service.ts
// Specifies JSON download
downloadJSON() {
this.download(this.title + '.txt', this.JSON, this.fileText)
}
// Specifies XML download
downloadXML() {
this.download(this.title + '.xml', this.XML, this.xmlFile['body']);
}
// Creates downloadable link and triggers download
download(filename, type, text) {
var element = document.createElement('a');
element.setAttribute('href', type + encodeURIComponent(text));
element.setAttribute('download', filename);
element.style.display = 'none';
document.body.appendChild(element);
element.click();
document.body.removeChild(element);
}
Bootbox.js can help you with that.
With: bootbox.prompt(message, callback)
With a simple:
bootbox.prompt("This is the default prompt!", function(result){ console.log(result); });
you can set an input box for the user to fill out the filename intented.
See Bootbox Prompt Examples

How to display dynamic url image in html from which created by javascript

I am trying to display the image directly in HTML through a dynamic link I generated by Javascript.
function dynamicUrl() {
var url = "http://xxx.xxx.xxx" + dynamic_variables + ".jpg";
return url;}
Most of my research, people display image by click on buttons
or what I can do for now is link to the image.
test
Anyone know how to directly display the image using the dynamic URL?
Thanks!
Dynamic create DOM for example:
function dynamicUrl() {
var url = "https://is1-ssl.mzstatic.com/image/thumb/Purple111/v4/dd/95/7e/dd957e3a-abd3-da8a-2211-726a67108938/source/256x256bb.jpg";
return url;
}
var img = document.createElement("img");
img.src = dynamicUrl();
document.body.appendChild(img);
Manipulate DOM to dynamic change img url:
function dynamicUrl() {
var url = "https://www.62icon.com/client/assets/img/like-icon.svg";
var img = document.getElementById('imageid');
img.src = url;
}
<div>
<p>Image goes here</p>
<button onclick="dynamicUrl()">Change Image</button>
</div>
<img id="imageid" src="https://is1-ssl.mzstatic.com/image/thumb/Purple111/v4/dd/95/7e/dd957e3a-abd3-da8a-2211-726a67108938/source/256x256bb.jpg" />
Adding a id for the link element
<a id="link" href="">test</a>
Using click event of link element
var link = document.getElementById("link");
link.onclick = function goToDynamicUrl() {
var url = "https://image.flaticon.com/teams/new/1-freepik.jpg";
window.location.href = url;
}
Here is another method:
<div id="dimg">Here add image</div>
<script>
var dimg = document.getElementById('dimg');
function addImg(dv){
dimg.innerHTML ='<img src="http://xxx.xxx.xxx'+ dv +'.jpg'" >';
}
addImg('imgname');
</script>

How to save a base64 image to user's disk using JavaScript?

I have converted the source content from the <img> html tag to a base64String using JavaScript. The image was displayed clearly. Now I want to save that image to user's disk using javascript.
<html>
<head>
<script>
function saveImageAs () {
var imgOrURL;
embedImage.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUA" +
"AAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO" +
"9TXL0Y4OHwAAAABJRU5ErkJggg==";
imgOrURL = embedImage;
if (typeof imgOrURL == 'object')
imgOrURL = embedImage.src;
window.win = open(imgOrURL);
setTimeout('win.document.execCommand("SaveAs")', 0);
}
</script>
</head>
<body>
<a href="#" ONCLICK="saveImageAs(); return false" >save image</a>
<img id="embedImage" alt="Red dot">
</body>
</html>
This code worked well when I set the image path as source for <img> html tag. However, when I pass the source as base64String does not work.
How to achieve what I want?
HTML5 download attribute
Just to allow user to download the image or other file you may use the HTML5 download attribute.
Static file download
<a href="/images/image-name.jpg" download>
<!-- OR -->
<a href="/images/image-name.jpg" download="new-image-name.jpg">
Dynamic file download
In cases requesting image dynamically it is possible to emulate such download.
If your image is already loaded and you have the base64 source then:
function saveBase64AsFile(base64, fileName) {
var link = document.createElement("a");
document.body.appendChild(link); // for Firefox
link.setAttribute("href", base64);
link.setAttribute("download", fileName);
link.click();
}
Otherwise if image file is downloaded as Blob you can use FileReader to convert it to Base64:
function saveBlobAsFile(blob, fileName) {
var reader = new FileReader();
reader.onloadend = function () {
var base64 = reader.result ;
var link = document.createElement("a");
document.body.appendChild(link); // for Firefox
link.setAttribute("href", base64);
link.setAttribute("download", fileName);
link.click();
};
reader.readAsDataURL(blob);
}
Firefox
The anchor tag you are creating also needs to be added to the DOM in Firefox, in order to be recognized for click events (Link).
IE is not supported: Caniuse link
In JavaScript you cannot have the direct access to the filesystem.
However, you can make browser to pop up a dialog window allowing the user to pick the save location. In order to do this, use the replace method with your Base64String and replace "image/png" with "image/octet-stream":
"data:image/png;base64,iVBORw0KG...".replace("image/png", "image/octet-stream");
Also, W3C-compliant browsers provide 2 methods to work with base64-encoded and binary data:
atob()
btoa()
Probably, you will find them useful in a way...
Here is a refactored version of what I understand you need:
window.addEventListener('DOMContentLoaded', () => {
const img = document.getElementById('embedImage');
img.src = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUA' +
'AAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO' +
'9TXL0Y4OHwAAAABJRU5ErkJggg==';
img.addEventListener('load', () => button.removeAttribute('disabled'));
const button = document.getElementById('saveImage');
button.addEventListener('click', () => {
window.location.href = img.src.replace('image/png', 'image/octet-stream');
});
});
<!DOCTYPE html>
<html>
<body>
<img id="embedImage" alt="Red dot" />
<button id="saveImage" disabled="disabled">save image</button>
</body>
</html>
This Works
function saveBase64AsFile(base64, fileName) {
var link = document.createElement("a");
document.body.appendChild(link);
link.setAttribute("type", "hidden");
link.href = "data:text/plain;base64," + base64;
link.download = fileName;
link.click();
document.body.removeChild(link);
}
Based on the answer above but with some changes
Check out https://github.com/eligrey/FileSaver.js/ which wraps the HTML5 method and provides workarounds for e.g. IE10.

Categories