Force browser to download image files on click - javascript
I need the browser to download the image files just as it does while clicking on an Excel sheet.
Is there a way to do this using client-side programming only?
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script type="text/javascript" src="Scripts/jquery-1.10.2.js">
$(document).ready(function () {
$("*").click(function () {
$("p").hide();
});
});
</script>
</head>
<script type="text/javascript">
document.onclick = function (e) {
e = e || window.event;
var element = e.target || e.srcElement;
if (element.innerHTML == "Image") {
//someFunction(element.href);
var name = element.nameProp;
var address = element.href;
saveImageAs1(element.nameProp, element.href);
return false; // Prevent default action and stop event propagation
}
else
return true;
};
function saveImageAs1(name, adress) {
if (confirm('you wanna save this image?')) {
window.win = open(adress);
//response.redirect("~/testpage.html");
setTimeout('win.document.execCommand("SaveAs")', 100);
setTimeout('win.close()', 500);
}
}
</script>
<body>
<form id="form1" runat="server">
<div>
<p>
Excel<br />
Image
</p>
</div>
</form>
</body>
</html>
How should it work in case of downloading an Excel sheet (what browsers do)?
Using HTML5 you can add the attribute 'download' to your links.
<a href="/path/to/image.png" download>
Compliant browsers will then prompt to download the image with the same file name (in this example image.png).
If you specify a value for this attribute, then that will become the new filename:
<a href="/path/to/image.png" download="AwesomeImage.png">
UPDATE: As of spring 2018 this is no longer possible for cross-origin hrefs. So if you want to create <a href="https://i.imgur.com/IskAzqA.jpg" download> on a domain other than imgur.com it will not work as intended. Chrome deprecations and removals announcement
I managed to get this working in Chrome and Firefox too by appending a link to the to document.
var link = document.createElement('a');
link.href = 'images.jpg';
link.download = 'Download.jpg';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
Leeroy & Richard Parnaby-King:
UPDATE: As of spring 2018 this is no longer possible for cross-origin
hrefs. So if you want to create on a domain other than imgur.com it
will not work as intended. Chrome deprecations and removals
announcement
function forceDownload(url, fileName){
var xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.responseType = "blob";
xhr.onload = function(){
var urlCreator = window.URL || window.webkitURL;
var imageUrl = urlCreator.createObjectURL(this.response);
var tag = document.createElement('a');
tag.href = imageUrl;
tag.download = fileName;
document.body.appendChild(tag);
tag.click();
document.body.removeChild(tag);
}
xhr.send();
}
A more modern approach using Promise and async/await :
async function toDataURL(url) {
const blob = await fetch(url).then(res => res.blob());
return URL.createObjectURL(blob);
}
then
async function download() {
const a = document.createElement("a");
a.href = await toDataURL("https://cdn1.iconfinder.com/data/icons/ninja-things-1/1772/ninja-simple-512.png");
a.download = "myImage.png";
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
}
Find documentation here: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
Update Spring 2018
<a href="/path/to/image.jpg" download="FileName.jpg">
While this is still supported, as of February 2018 chrome disabled this feature for cross-origin downloading meaning this will only work if the file is located on the same domain name.
I figured out a workaround for downloading cross domain images after Chrome's new update which disabled cross domain downloading. You could modify this into a function to suit your needs. You might be able to get the image mime-type (jpeg,png,gif,etc) with some more research if you needed to. There may be a way to do something similar to this with videos as well. Hope this helps someone!
Leeroy & Richard Parnaby-King:
UPDATE: As of spring 2018 this is no longer possible for cross-origin
hrefs. So if you want to create on a domain other
than imgur.com it will not work as intended. Chrome deprecations and
removals announcement
var image = new Image();
image.crossOrigin = "anonymous";
image.src = "https://is3-ssl.mzstatic.com/image/thumb/Music62/v4/4b/f6/a2/4bf6a267-5a59-be4f-6947-d803849c6a7d/source/200x200bb.jpg";
// get file name - you might need to modify this if your image url doesn't contain a file extension otherwise you can set the file name manually
var fileName = image.src.split(/(\\|\/)/g).pop();
image.onload = function () {
var canvas = document.createElement('canvas');
canvas.width = this.naturalWidth; // or 'width' if you want a special/scaled size
canvas.height = this.naturalHeight; // or 'height' if you want a special/scaled size
canvas.getContext('2d').drawImage(this, 0, 0);
var blob;
// ... get as Data URI
if (image.src.indexOf(".jpg") > -1) {
blob = canvas.toDataURL("image/jpeg");
} else if (image.src.indexOf(".png") > -1) {
blob = canvas.toDataURL("image/png");
} else if (image.src.indexOf(".gif") > -1) {
blob = canvas.toDataURL("image/gif");
} else {
blob = canvas.toDataURL("image/png");
}
$("body").html("<b>Click image to download.</b><br><a download='" + fileName + "' href='" + blob + "'><img src='" + blob + "'/></a>");
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
var pom = document.createElement('a');
pom.setAttribute('href', 'data:application/octet-stream,' + encodeURIComponent(text));
pom.setAttribute('download', filename);
pom.style.display = 'none';
document.body.appendChild(pom);
pom.click();
document.body.removeChild(pom);
This is a general solution to your problem. But there is one very important part that the file extension should match your encoding. And of course, that content parameter of downlowadImage function should be base64 encoded string of your image.
const clearUrl = url => url.replace(/^data:image\/\w+;base64,/, '');
const downloadImage = (name, content, type) => {
var link = document.createElement('a');
link.style = 'position: fixed; left -10000px;';
link.href = `data:application/octet-stream;base64,${encodeURIComponent(content)}`;
link.download = /\.\w+/.test(name) ? name : `${name}.${type}`;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
['png', 'jpg', 'gif'].forEach(type => {
var download = document.querySelector(`#${type}`);
download.addEventListener('click', function() {
var img = document.querySelector('#img');
downloadImage('myImage', clearUrl(img.src), type);
});
});
a gif image: <image id="img" src="data:image/gif;base64,R0lGODlhPQBEAPeoAJosM//AwO/AwHVYZ/z595kzAP/s7P+goOXMv8+fhw/v739/f+8PD98fH/8mJl+fn/9ZWb8/PzWlwv///6wWGbImAPgTEMImIN9gUFCEm/gDALULDN8PAD6atYdCTX9gUNKlj8wZAKUsAOzZz+UMAOsJAP/Z2ccMDA8PD/95eX5NWvsJCOVNQPtfX/8zM8+QePLl38MGBr8JCP+zs9myn/8GBqwpAP/GxgwJCPny78lzYLgjAJ8vAP9fX/+MjMUcAN8zM/9wcM8ZGcATEL+QePdZWf/29uc/P9cmJu9MTDImIN+/r7+/vz8/P8VNQGNugV8AAF9fX8swMNgTAFlDOICAgPNSUnNWSMQ5MBAQEJE3QPIGAM9AQMqGcG9vb6MhJsEdGM8vLx8fH98AANIWAMuQeL8fABkTEPPQ0OM5OSYdGFl5jo+P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png">Download PNG</button>
<button id="jpg">Download JPG</button>
<button id="gif">Download GIF</button>
Create a function that recibe the image url and file name and call the funcion using a button.
function downloadImage(url, name){
fetch(url)
.then(resp => resp.blob())
.then(blob => {
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.style.display = 'none';
a.href = url;
// the filename you want
a.download = name;
document.body.appendChild(a);
a.click();
window.URL.revokeObjectURL(url);
})
.catch(() => alert('An error sorry'));
}
<button onclick="downloadImage('https://upload.wikimedia.org/wikipedia/commons/thumb/0/02/Stack_Overflow_logo.svg/1280px-Stack_Overflow_logo.svg.png', 'LogoStackOverflow.png')" >DOWNLOAD</button>
Codepen.io Force image download with JavaScript
vladi.codes
You can directly download this file using anchor tag without much code.Copy the snippet and paste in your text-editor and try it...!
<html>
<head>
</head>
<body>
<div>
<img src="https://upload.wikimedia.org/wikipedia/commons/1/1f/SMirC-thumbsup.svg" width="200" height="200">
Download Image
</div>
</body>
</html>
In 2020 I use Blob to make local copy of image, which browser will download as a file. You can test it on this site.
(function(global) {
const next = () => document.querySelector('.search-pagination__button-text').click();
const uuid = () => Math.random().toString(36).substring(7);
const toBlob = (src) => new Promise((res) => {
const img = document.createElement('img');
const c = document.createElement("canvas");
const ctx = c.getContext("2d");
img.onload = ({target}) => {
c.width = target.naturalWidth;
c.height = target.naturalHeight;
ctx.drawImage(target, 0, 0);
c.toBlob((b) => res(b), "image/jpeg", 0.75);
};
img.crossOrigin = "";
img.src = src;
});
const save = (blob, name = 'image.png') => {
const a = document.createElement("a");
a.href = URL.createObjectURL(blob);
a.target = '_blank';
a.download = name;
a.click();
};
global.download = () => document.querySelectorAll('.search-content__gallery-results figure > img[src]').forEach(async ({src}) => save(await toBlob(src), `${uuid()}.png`));
global.next = () => next();
})(window);
Try this:
<a class="button" href="http://www.glamquotes.com/wp-content/uploads/2011/11/smile.jpg" download="smile.jpg">Download image</a>
You can do
const urls = ['image.png', 'image1.png'];
urls.forEach((url) => {
window.open(url, "_blank");
});
// Pass desired URL as a param
function saveAs(uri) {
fetch(uri)
.then(res => res.blob()) // Gets the response and returns it as a blob
.then(blob => {
// Here, I use it to make an image appear on the page
let objectURL = URL.createObjectURL(blob);
let myImage = new Image();
myImage.href = blob;
myImage.download = generateFileName();
//Firefox requires the link to be in the body
document.body.appendChild(myImage);
//simulate click
myImage.click();
//remove the link when done
document.body.removeChild(myImage);
});
}
// Generate filenames for the image which is to be downloaded
function generateFileName() {
return `img${Math.floor(Math.random() * 90000) + 10000}`;
}
<html>
<head>
<script type="text/javascript">
function prepHref(linkElement) {
var myDiv = document.getElementById('Div_contain_image');
var myImage = myDiv.children[0];
linkElement.href = myImage.src;
}
</script>
</head>
<body>
<div id="Div_contain_image"><img src="YourImage.jpg" alt='MyImage'></div>
<a href="#" onclick="prepHref(this)" download>Click here to download image</a>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<button onclick="forceDownload('http://localhost:4000/1-2-free-png-image.png','test.png')">Download</button>
<script>
function forceDownload(url, fileName){
var xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.responseType = "blob";
xhr.onload = function(){
var urlCreator = window.URL || window.webkitURL;
var imageUrl = urlCreator.createObjectURL(this.response);
var tag = document.createElement('a');
tag.href = imageUrl;
tag.download = fileName;
document.body.appendChild(tag);
tag.click();
document.body.removeChild(tag);
}
xhr.send();
}
</script>
</body>
</html>
I found that
<a href="link/to/My_Image_File.jpeg" download>Download Image File</a>
did not work for me. I'm not sure why.
I have found that you can include a ?download=true parameter at the end of your link to force a download. I think I noticed this technique being used by Google Drive.
In your link, include ?download=true at the end of your href.
You can also use this technique to set the filename at the same time.
In your link, include ?download=true&filename=My_Image_File.jpeg at the end of your href.
What about using the .click() function and the tag?
(Compressed version)
<a id="downloadtag" href="examplefolder/testfile.txt" hidden download></a>
<button onclick="document.getElementById('downloadtag').click()">Download</button>
Now you can trigger it with js. It also doesn't open, as other examples, image and text files!
(js-function version)
function download(){
document.getElementById('downloadtag').click();
}
<!-- HTML -->
<button onclick="download()">Download</button>
<a id="downloadtag" href="coolimages/awsome.png" hidden download></a>
You don't need to write js to do that, simply use:
Download image
And the browser itself will automatically download the image.
If for some reason it doesn't work add the download attribute.
With this attribute you can set a name for the downloadable file:
Download image
Related
How to write data in JSON file in the EJS template file [duplicate]
I want to Write Data to existing file using JavaScript. I don't want to print it on console. I want to Actually Write data to abc.txt. I read many answered question but every where they are printing on console. at some place they have given code but its not working. So please can any one help me How to actually write data to File. I referred the code but its not working: its giving error: Uncaught TypeError: Illegal constructor on chrome and SecurityError: The operation is insecure. on Mozilla var f = "sometextfile.txt"; writeTextFile(f, "Spoon") writeTextFile(f, "Cheese monkey") writeTextFile(f, "Onion") function writeTextFile(afilename, output) { var txtFile =new File(afilename); txtFile.writeln(output); txtFile.close(); } So can we actually write data to file using only Javascript or NOT?
You can create files in browser using Blob and URL.createObjectURL. All recent browsers support this. You can not directly save the file you create, since that would cause massive security problems, but you can provide it as a download link for the user. You can suggest a file name via the download attribute of the link, in browsers that support the download attribute. As with any other download, the user downloading the file will have the final say on the file name though. var textFile = null, makeTextFile = function (text) { var data = new Blob([text], {type: 'text/plain'}); // If we are replacing a previously generated file we need to // manually revoke the object URL to avoid memory leaks. if (textFile !== null) { window.URL.revokeObjectURL(textFile); } textFile = window.URL.createObjectURL(data); // returns a URL you can use as a href return textFile; }; Here's an example that uses this technique to save arbitrary text from a textarea. If you want to immediately initiate the download instead of requiring the user to click on a link, you can use mouse events to simulate a mouse click on the link as Lifecube's answer did. I've created an updated example that uses this technique. var create = document.getElementById('create'), textbox = document.getElementById('textbox'); create.addEventListener('click', function () { var link = document.createElement('a'); link.setAttribute('download', 'info.txt'); link.href = makeTextFile(textbox.value); document.body.appendChild(link); // wait for the link to be added to the document window.requestAnimationFrame(function () { var event = new MouseEvent('click'); link.dispatchEvent(event); document.body.removeChild(link); }); }, false);
Some suggestions for this - If you are trying to write a file on client machine, You can't do this in any cross-browser way. IE does have methods to enable "trusted" applications to use ActiveX objects to read/write file. If you are trying to save it on your server then simply pass on the text data to your server and execute the file writing code using some server side language. To store some information on the client side that is considerably small, you can go for cookies. Using the HTML5 API for Local Storage.
If you are talking about browser javascript, you can not write data directly to local file for security reason. HTML 5 new API can only allow you to read files. But if you want to write data, and enable user to download as a file to local. the following code works: function download(strData, strFileName, strMimeType) { var D = document, A = arguments, a = D.createElement("a"), d = A[0], n = A[1], t = A[2] || "text/plain"; //build download link: a.href = "data:" + strMimeType + "charset=utf-8," + escape(strData); if (window.MSBlobBuilder) { // IE10 var bb = new MSBlobBuilder(); bb.append(strData); return navigator.msSaveBlob(bb, strFileName); } /* end if(window.MSBlobBuilder) */ if ('download' in a) { //FF20, CH19 a.setAttribute("download", n); a.innerHTML = "downloading..."; D.body.appendChild(a); setTimeout(function() { var e = D.createEvent("MouseEvents"); e.initMouseEvent("click", true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null); a.dispatchEvent(e); D.body.removeChild(a); }, 66); return true; }; /* end if('download' in a) */ //do iframe dataURL download: (older W3) var f = D.createElement("iframe"); D.body.appendChild(f); f.src = "data:" + (A[2] ? A[2] : "application/octet-stream") + (window.btoa ? ";base64" : "") + "," + (window.btoa ? window.btoa : escape)(strData); setTimeout(function() { D.body.removeChild(f); }, 333); return true; } to use it: download('the content of the file', 'filename.txt', 'text/plain');
Try let a = document.createElement('a'); a.href = "data:application/octet-stream,"+encodeURIComponent("My DATA"); a.download = 'abc.txt'; a.click(); If you want to download binary data look here Update 2020.06.14 I upgrade Chrome to 83.0 and above SO snippet stop works (reason: sandbox security restrictions) - but JSFiddle version works - here
Above answer is useful but, I found code which helps you to download text file directly on button click. In this code you can also change filename as you wish. It's pure javascript function with HTML5. Works for me! function saveTextAsFile() { var textToWrite = document.getElementById("inputTextToSave").value; var textFileAsBlob = new Blob([textToWrite], {type:'text/plain'}); var fileNameToSaveAs = document.getElementById("inputFileNameToSaveAs").value; var downloadLink = document.createElement("a"); downloadLink.download = fileNameToSaveAs; downloadLink.innerHTML = "Download File"; if (window.webkitURL != null) { // Chrome allows the link to be clicked // without actually adding it to the DOM. downloadLink.href = window.webkitURL.createObjectURL(textFileAsBlob); } else { // Firefox requires the link to be added to the DOM // before it can be clicked. downloadLink.href = window.URL.createObjectURL(textFileAsBlob); downloadLink.onclick = destroyClickedElement; downloadLink.style.display = "none"; document.body.appendChild(downloadLink); } downloadLink.click(); }
const data = {name: 'Ronn', age: 27}; //sample json const a = document.createElement('a'); const blob = new Blob([JSON.stringify(data)]); a.href = URL.createObjectURL(blob); a.download = 'sample-profile'; //filename to download a.click(); Check Blob documentation here - Blob MDN to provide extra parameters for file type. By default it will make .txt file
In the case it is not possibile to use the new Blob solution, that is for sure the best solution in modern browser, it is still possible to use this simpler approach, that has a limit in the file size by the way: function download() { var fileContents=JSON.stringify(jsonObject, null, 2); var fileName= "data.json"; var pp = document.createElement('a'); pp.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(fileContents)); pp.setAttribute('download', fileName); pp.click(); } setTimeout(function() {download()}, 500); $('#download').on("click", function() { function download() { var jsonObject = { "name": "John", "age": 31, "city": "New York" }; var fileContents = JSON.stringify(jsonObject, null, 2); var fileName = "data.json"; var pp = document.createElement('a'); pp.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(fileContents)); pp.setAttribute('download', fileName); pp.click(); } setTimeout(function() { download() }, 500); }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button id="download">Download me</button>
Use the code by the user #useless-code above (https://stackoverflow.com/a/21016088/327386) to generate the file. If you want to download the file automatically, pass the textFile that was just generated to this function: var downloadFile = function downloadURL(url) { var hiddenIFrameID = 'hiddenDownloader', iframe = document.getElementById(hiddenIFrameID); if (iframe === null) { iframe = document.createElement('iframe'); iframe.id = hiddenIFrameID; iframe.style.display = 'none'; document.body.appendChild(iframe); } iframe.src = url; }
I found good answers here, but also found a simpler way. The button to create the blob and the download link can be combined in one link, as the link element can have an onclick attribute. (The reverse seems not possible, adding a href to a button does not work.) You can style the link as a button using bootstrap, which is still pure javascript, except for styling. Combining the button and the download link also reduces code, as fewer of those ugly getElementById calls are needed. This example needs only one button click to create the text-blob and download it: <a id="a_btn_writetofile" download="info.txt" href="#" class="btn btn-primary" onclick="exportFile('This is some dummy data.\nAnd some more dummy data.\n', 'a_btn_writetofile')" > Write To File </a> <script> // URL pointing to the Blob with the file contents var objUrl = null; // create the blob with file content, and attach the URL to the downloadlink; // NB: link must have the download attribute // this method can go to your library function exportFile(fileContent, downloadLinkId) { // revoke the old object URL to avoid memory leaks. if (objUrl !== null) { window.URL.revokeObjectURL(objUrl); } // create the object that contains the file data and that can be referred to with a URL var data = new Blob([fileContent], { type: 'text/plain' }); objUrl = window.URL.createObjectURL(data); // attach the object to the download link (styled as button) var downloadLinkButton = document.getElementById(downloadLinkId); downloadLinkButton.href = objUrl; }; </script>
Here is a single-page local-file version for use when you need the extra processing functionality of a scripting language. Save the code below to a text file Change the file extension from '.txt' to '.html' Right-click > Open With... > notepad Program word processing as needed, then save Double-click html file to open in default browser Result will be previewed in the black box, click download to get the resulting text file Code: <!DOCTYPE HTML> <HTML> <HEAD> </HEAD> <BODY> <SCRIPT> // do text manipulation here let string1 = 'test\r\n'; let string2 = 'export.'; // assemble final string const finalText = string1 + string2; // convert to blob const data = new Blob([finalText], {type: 'text/plain'}); // create file link const link = document.createElement('a'); link.innerHTML = 'download'; link.setAttribute('download', 'data.txt'); link.href = window.URL.createObjectURL(data); document.body.appendChild(link); // preview the output in a paragraph const htmlBreak = string => { return string.replace(/(?:\r\n|\r|\n)/g, '<br>'); } const preview = document.createElement('p'); preview.innerHTML = htmlBreak(finalText); preview.style.border = "1px solid black"; document.body.appendChild(preview); </SCRIPT> </BODY> </HTML>
HTML Editor with Download Option
I'm looking for a way to add a download feature to my JS that will create a file using the programming that a user might enter in, lets say, a <textarea>. Are there any features in JS that would work similar to this? (HTML Format!!) var x = document.write("<p>Hi!</p>"); window.replace(x); And then: <button onclick="open()">Save</button> <script> var hi = document.write("<p>hi</p>;"); open() { window.open(hi) } </script> After they opened the variable on the new page, the user could use ctrl + s to save the page displayed. Ideas? Thanks in advance.
<textarea id="text-val" rows="4" style="height: 80%;width: 90%;"></textarea><br/><br/> <input type="button" id="dwn-btn" value="Save" /> <script> function download(filename, text) { var element = document.createElement('a'); element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text)); element.setAttribute('download', filename); element.style.display = 'none'; document.body.appendChild(element); element.click(); document.body.removeChild(element); } document.getElementById("dwn-btn").addEventListener("click", function() { var text = document.getElementById("text-val").value; var filename = "example.html"; download(filename, text); }, false); </script> I hope this is what you are expecting
Create new Blob from your html script with application/octet-stream mime type. Then use URL.createOjectURL api to generate download link. And navigate to that link. In this example code I navigated using creating temporary link (<a>) element. function download() { var blobPart = ['<h1>Test</h1>']; var blob = new Blob(blobPart, { type: "application/octet-stream" }); var urlObj = URL.createObjectURL(blob); var a = document.createElement('a'); document.body.appendChild(a); a.href = urlObj; a.download = 'filename.html'; a.click(); a.remove(); } document.getElementById('download-btn').addEventListener('click', download); Download
Client side Javascript get video width/height before upload
I've been trying to piece together a combination of HTML5 video tag + the FileReader API but I haven't figured out how to get the dimensions of a video that a user is providing from their own computer. Here is what I am referencing for width/ height: HTML5 Video Dimensions <video id="foo" src="foo.mp4"></video> var vid = document.getElementById("foo"); vid.videoHeight; // returns the intrinsic height of the video vid.videoWidth; // returns the intrinsic width of the video But I want to know if it's possible to do this with a file from a user's computer (that they have selected via a normal input html tag). Thanks!
A bit unclean solution using basic FileReader + Data URL. <html> <head> <style> div { margin: 20px; } </style> </head> <body> <h1>Get Dimensions</h1> <div> <label for="load-file">Load a file:</label> <input type="file" id="load-file"> </div> <div> <button type="button" id="done-button">Get me dimensions</button> </div> <script src="//cdn.jsdelivr.net/jquery/2.1.4/jquery.js"></script> <script> (function ($) { $('#done-button').on('click', function () { var file = $('#load-file')[0].files[0]; var reader = new FileReader(); var fileType = file.type; console.log("type", fileType); reader.addEventListener("load", function () { var dataUrl = reader.result; var videoId = "videoMain"; var $videoEl = $('<video id="' + videoId + '"></video>'); $("body").append($videoEl); $videoEl.attr('src', dataUrl); var videoTagRef = $videoEl[0]; videoTagRef.addEventListener('loadedmetadata', function(e){ console.log(videoTagRef.videoWidth, videoTagRef.videoHeight); }); }, false); if (file) { reader.readAsDataURL(file); } }); })(jQuery); </script> </body> </html>
Here is a simple and fast solution to get a video's size before upload. It doesn't require any dependency. const url = URL.createObjectURL(file); const $video = document.createElement("video"); $video.src = url; $video.addEventListener("loadedmetadata", function () { console.log("width:", this.videoWidth); console.log("height:", this.videoHeight); });
const onSelectVideo = (files) => { const file = files[0]; const url = URL.createObjectURL(file); let videoId = "videoMain"; const video = document.createElement("video"); const body = document.getElementsByTagName("body"); video.setAttribute("src", url); video.setAttribute("videoId", videoId); body[0]?.append(video); let videoTagRef = document.querySelector("[videoId='videoMain']"); videoTagRef.addEventListener("loadedmetadata", function (e) { console.log(videoTagRef.videoWidth, videoTagRef.videoHeight); });}
Downloading or rendering on an Iframe depending on app Logic in Angular JS
I have an angular JS app on which I download a pdf file and then create a blob from it. Like this: vm.fileData = new ApiDownloadFile({fileId: 1}); return vm.fileData.$query() .then(function(response) { try{ console.log("Try..." + new Date()); $log.log(response); var arrayBufferView = new Uint8Array(response.Body.data); $log.log(arrayBufferView); var file = new Blob( [arrayBufferView], {type: response.ContentType}); var link = document.createElement('a'); link.href = window.URL.createObjectURL(file); link.download = response.fileName; link.click(); console.log("After..." + new Date()); console.log("GENERATED LINK: "+link.href); //PDFObject.embed(link.href, "#my-container"); } catch(e) { console.log("Execption..."); // TypeError old chrome and FF window.BlobBuilder = window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder || window.MSBlobBuilder; if (e.name == 'TypeError' && window.BlobBuilder) { var bb = new BlobBuilder(); bb.append(response.Body.data); var file = bb.getBlob("image/jpeg"); var link = document.createElement('a'); link.href = window.URL.createObjectURL(file); link.download = "1.jpg"; //link.click(); } else if (e.name == "InvalidStateError") { // InvalidStateError (tested on FF13 WinXP) var jpeg = new Blob(response.Body.data, {type: "image/jpeg"}); } else { // We're screwed, blob constructor unsupported entirely } } },function(err) { $log.log(err); }); }; I can donwload the file easily by creating an 'a' element and then clicking it. However I would like to be able to either download it on the browser or render it on an Iframe I have in my view. The logic should be something like this: if download == true: create the <a> element and click it to download file. else: render the pdf on an iframe and don´t download on browser. However I´m not able to get the blob URL to be rendered on the Iframe. I´m using PDFObject to visualize the PDF. Can anyone help me achieve this?
Do this in your page <iframe ng-if="IframeManager.Url" ng-src="{{ IframeManager.Url }}"></iframe> Then in your controller add $scope.Download = true; $scope.IframeManager = { Show: function (url) { $scope.IframeManager.Url = url; }, Hide: function () { $scope.IframeManager.Url = null; } }; So if you want to show the file you do your preview routine blob conversion and get the url if ($scope.Download) { var link = document.createElement('a'); link.href = window.URL.createObjectURL(file); link.download = response.fileName; link.click(); console.log("After..." + new Date()); console.log("GENERATED LINK: "+link.href); } else { $scope.IframeManager.Show(window.URL.createObjectURL(file)); }
How to read file content in a javascript variable?
I got a small script to split the text inside 'var foo' after every 4 characters. It is working fine. but my actual data is in a text file say 'a.txt'. How do I take this entire file text in 'var foo'. and write the split output to another text file? var foo = "this is sample text !!!"; var arr = []; for (var i = 0; i < foo.length; i++) { if (i % 4 == 0 && i != 0) arr.push(foo.substring(i - 4, i)); if (i == foo.length - 1) arr.push(foo.substring(i - (i % 4), i+1)); } document.write(arr); console.log(arr);
To get the content of the file you need to select a file using an input tag. <!DOCTYPE html> <head> <meta charset="UTF-8"> </head> <body> <input id="input" type="file" accept="text/plain"> <script src="script.js"></script> </body> A good moment to read the content of the file is in the change event. const input = document.querySelector("#input"); input.addEventListener("change", () => { const file = input.files.item(0); }); To read the content of the file as a string you need to convert it. function fileToText(file, callback) { const reader = new FileReader(); reader.readAsText(file); reader.onload = () => { callback(reader.result); }; } The content of the file as a string will be available to the the callback function. You can create a link and use the click event to download the string into a text file. function save(content, fileName, mime) { const blob = new Blob([content], { tipe: mime }); const url = URL.createObjectURL(blob); const a = document.createElement("a"); a.href = url; a.download = fileName; a.click(); } Here is the complete code const input = document.querySelector("#input"); input.addEventListener("change", () => { const file = input.files.item(0); fileToText(file, (text) => { save(text, "fileName.txt", "text/plain"); }); }); function fileToText(file, callback) { const reader = new FileReader(); reader.readAsText(file); reader.onload = () => { callback(reader.result); }; } function save(content, fileName, mime) { const blob = new Blob([content], { tipe: mime }); const url = URL.createObjectURL(blob); const a = document.createElement("a"); a.href = url; a.download = fileName; a.click(); } <!DOCTYPE html> <head> <meta charset="UTF-8"> </head> <body> <input id="input" type="file" accept="text/plain"> <script src="script.js"></script> </body> You can read more about manipulating files in JavaScript here: https://www.html5rocks.com/en/tutorials/file/dndfiles/
Solution to this helped me : How do I load the contents of a text file into a javascript variable? var client = new XMLHttpRequest(); client.open('GET', '/foo.txt'); client.onreadystatechange = function() { alert(client.responseText); } client.send();