I have a function in my web app that allows me to download a present image. What I would also like it to do is give me the opportunity to save this file under the name upon download.
My function is this:
function saveFile(){
var dataURL = canvas.toDataURL("image/png").replace("image/png", "image/octet-stream");
console.log(dataURL);
window.location.href = dataURL;
}
And how can I do to name this file?
Thank u all!
First create anchor tag and add href and download attribute to provide the uri and fileName respectively.
function saveFile(){
var dataURL = canvas.toDataURL("image/png").replace("image/png", "image/octet-stream");
console.log(dataURL);
const anchorLink = document.createElement('a');
document.body.appendChild(anchorLink)
anchorLink.href = dataURL;
anchorLink.download = "file_name.png";
anchorLink.click();
document.body.removeChild(anchorLink)
}
I have basic html page where I want to upload image file, and after closing or reloading page I want that image to be there.
HTML code is :
<input type='file' accept="image/*">
<img alt="your image" height=400 width=auto>
Javascript code:
let img = document.querySelector('img');
document.body.onload = () => {
if(localStorage.image){
let source = JSON.parse(localStorage.image)
let file = new File([source], 'download.jpg', {type: 'image/jpeg', lastModified: Date.now()})
img.src = URL.createObjectURL(file)
}
}
document.querySelector('input[type="file"]').addEventListener('change', function() {
img.src = URL.createObjectURL(this.files[0])
localStorage.image = JSON.stringify(img.src)
});
My questions are:
When I console.log(localStorage.image), after uploading and reloading page, I will get one blob, and because from security reasons I can't use same blob, I tried to make new File and then from that file to create blob that I can later use, but when I console.log new blob (conosle.log(img.src)) I received different blob, so my question is why that happened, is there a way to correct that, I see that these two files has different file.size but when I want to change that it stays same
Also is there a second way to do that
As you can't persist blob objects between sessions (the blob URL will expire), you need to use a serializable format such as a data URL. Using a FileReader you can read the image file straight to a data url, and this can be stored in localStorage.
const fileReader = new FileReader();
fileReader.addEventListener('loadend', function() {
img.src = fileReader.result;
storage['image'] = fileReader.result;
})
document.querySelector('input[type="file"]').addEventListener('change', function() {
if (this.files.length > 0) {
fileReader.readAsDataURL(this.files[0]);
}
});
Here is a pen where I modified your code to use FileReader and data URLs (had to use sessionStorage because of codepen but localStorage should work)
https://codepen.io/Douile/pen/gOwORea?editors=1011
i want to give the file location url for the code to get my file instead of using input file in html part , to pass the file to the code
the code pasted below works if i use " input type= "file" " to get the file, but if i use url (like below) it gives a error
fileInput1.addEventListener is not a function
at window.onload
here is the code
window.onload = function() {
var z ="C:/Users/akash/Desktop/riidl/UTham.txt"
var fileInput1 = z;
if (fileInput1){
fileInput1.addEventListener('change', function(e) {
var file = fileInput1.files[0];
var textType = /text.*/;
if (file.type.match(textType)) {
var reader = new FileReader();
reader.onload = function(e) {
spamdata=reader.result;
document.getElementById('here').onclick = console.log(spamdata);
}
reader.readAsText(file);
}
});
}
}
Accessing local files is not allowed in JavaScript for security purposes.
Pl refer to this answer for more details.
https://stackoverflow.com/a/372333/3626796
I have a function that sends data through data:JSON.stringify(formdata)using POST to a remove .NET webservice. I have no problem this far. What I want to do it to add also add a another value to the formdata JSON that will hold a base64 image data and send it to the server, and there I will convert it back to a JPEG image.
How can I so that? I already have a preview function that created a preview, but also create a base64 image:
function previewFile() {
var preview = document.querySelector('.uploadimage');
var file = document.querySelector('input[type=file]').files[0];
var reader = new FileReader();
reader.addEventListener("load", function () {
preview.src = reader.result;
}, false);
if (file) {
reader.readAsDataURL(file);
}
}
I see many question people asking how to upload image to the server. I want to stay with the current configuration but just pass the base64 image data to the server as a string. I see many developers struggling with that, and most of them just engine up creating a form in javascript and submitting like that.
Here is a recent way I did this:
string base64 = base64string.Substring(base64string.IndexOf(',') + 1);
byte[] imageData = Convert.FromBase64String(base64);
Image img;
using (var ms = new MemoryStream(imageData, 0, imageData.Length)) {
img = Image.FromStream(ms, true);
You will need:
using System.Drawing;
OR to simply convert to a jpg, use this:
File.WriteAllBytes("image.jpeg", Convert.FromBase64String(base64));
For sending the data I use the following JS:
function sendImage() {
if (this.files && this.files[0]) {
var FR = new FileReader();
FR.onload = function (e) {
$("#imgImage").attr("src", e.target.result); //show a preview
//send e.target.result as a string to your webservice
};
FR.readAsDataURL(this.files[0]);
}
}
I use this event to listen for uploaded files:
document.getElementById("fileid").addEventListener("change", sendImage, false);
And the front end:
<input type="file" id="fileid" />
I have a base64-encoded image from the server for which I want to force the download through JavaScript. Is is possible?
If you want to download it using JavaScript (without any back-end) use:
window.location.href = 'data:application/octet-stream;base64,' + img;
where img is your base64 encoded image.
If you want to allow the user to specify a file name, use the download attribute of the a tag:
<a download="FILENAME.EXT" href="data:image/png;base64,asdasd...">Download</a>
Notice: The download attribute is not supported by very old browsers
Simple way to do this with Javascript...
var a = document.createElement("a"); //Create <a>
a.href = "data:image/png;base64," + ImageBase64; //Image Base64 Goes here
a.download = "Image.png"; //File name Here
a.click(); //Downloaded file
It is so simple just use function below:
// Parameters:
// contentType: The content type of your file.
// its like application/pdf or application/msword or image/jpeg or
// image/png and so on
// base64Data: Its your actual base64 data
// fileName: Its the file name of the file which will be downloaded.
function downloadBase64File(contentType, base64Data, fileName) {
const linkSource = `data:${contentType};base64,${base64Data}`;
const downloadLink = document.createElement("a");
downloadLink.href = linkSource;
downloadLink.download = fileName;
downloadLink.click();
}
I found this solution from the sourcecode of how Chrome takes full-page screenshots.
const base64string = "";
const pageImage = new Image();
pageImage.src = 'data:image/png;base64,' + base64string;
pageImage.onload = function() {
const canvas = document.createElement('canvas');
canvas.width = pageImage.naturalWidth;
canvas.height= pageImage.naturalHeight;
const ctx = canvas.getContext('2d');
ctx.imageSmoothingEnabled = false;
ctx.drawImage(pageImage, 0, 0);
console.log(canvas, pageImage)
saveScreenshot(canvas);
}
function saveScreenshot(canvas) {
let fileName = "image"
const link = document.createElement('a');
link.download = fileName + '.png';
console.log(canvas)
canvas.toBlob(function(blob) {
console.log(blob)
link.href = URL.createObjectURL(blob);
link.click();
});
};
I don't know whether am late to answer this, but I think the better solution could be this.
Create a file from the base64string
const convertBase64ToFile = (base64String, fileName) => {
let arr = base64String.split(',');
let mime = arr[0].match(/:(.*?);/)[1];
let bstr = atob(arr[1]);
let n = bstr.length;
let uint8Array = new Uint8Array(n);
while (n--) {
uint8Array[n] = bstr.charCodeAt(n);
}
let file = new File([uint8Array], fileName, { type: mime });
return file;
}
Install File Saver from npm with
npm install file-saver
Import File Saver
const { saveAs } = require('file-saver');
/// OR
import { saveAs } from 'file-saver';
Using File Saver download the file
const downloadBase64Data = (base64String, fileName) => {
let file = convertBase64ToFile(base64String, fileName);
saveAs(file, fileName);
}
If this Answer has worked for you please upvote it and mark it as correct to help others easily find it
You can try this :
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Download Text File DataURL Demo</title>
<style>
body{ font: menu; }
</style>
<script src='//js.zapjs.com/js/download.js'></script>
</head>
<body>
<h1>Download Text File DataURL Demo</h1>
<main></main>
<script>
download("data:application/octet-stream;base64,YOUR BASE64URL", "dlDataUrlText.jpeg", "application/octet-stream;base64");
</script>
</body>
</html>
download tag downloads the image using the script included.
For reference you can try this URL : http://danml.com/download.html
In my Angular App, I am getting the base 64 files from server.
In Html:-
<button type="button" (click)="downloadFile(fileName,base64data,fileType)"></button>
In Ts:-
downloadFile(fileName:string,data: any,fileFormat:string): void {
const linkSource = 'data:'+fileFormat+';base64'+data;
const downloadLink = document.createElement("a");
downloadLink.href = linkSource;
downloadLink.download = fileName;
downloadLink.click();
}
If you already have it in base64, add the image tag in front of the base64. attach it to the element
png64 = "data:image/" + png64;
$('#downloadPNG').attr('href', png64);
Add the file name that you want when downloading to the download tag.
<a download="chart.png" id="downloadPNG">Export img</a>
In my React App, I was getting the base 64 images from an API, I stored it in a global prop and downloaded it with the help of <a> tag.
<a href={`data:application/octet-stream;base64,${this.props.base64image}`} download={"imageName"}>Click to Download the image</a>
At first: This question is extremly browser dependent! I tried many, so I came up to answer this question that way:
You should put the base64-Data inside the src-Tag of an IMG-Element:
How to display Base64 images in HTML?
Then you can right click the Image and click "Save Image..." (or similar) in these browsers:
Chrome 79
Edge 44
Firefox 71
IE 11
Safari 13
Also on Android with Chrome and Firefox.
Biggest file working was 23 MB PNG-File in IE 11 and Safari 13. But Firefox and Chrome did also work for 86 MB JPEG.