Related
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>
Is there any way to find out the file size before uploading the file using AJAX / PHP in change event of input file?
For the HTML bellow
<input type="file" id="myFile" />
try the following:
//binds to onchange event of your input field
$('#myFile').bind('change', function() {
//this.files[0].size gets the size of your file.
alert(this.files[0].size);
});
See following thread:
How to check file input size with jQuery?
<script type="text/javascript">
function AlertFilesize(){
if(window.ActiveXObject){
var fso = new ActiveXObject("Scripting.FileSystemObject");
var filepath = document.getElementById('fileInput').value;
var thefile = fso.getFile(filepath);
var sizeinbytes = thefile.size;
}else{
var sizeinbytes = document.getElementById('fileInput').files[0].size;
}
var fSExt = new Array('Bytes', 'KB', 'MB', 'GB');
fSize = sizeinbytes; i=0;while(fSize>900){fSize/=1024;i++;}
alert((Math.round(fSize*100)/100)+' '+fSExt[i]);
}
</script>
<input id="fileInput" type="file" onchange="AlertFilesize();" />
Work on IE and FF
Here's a simple example of getting the size of a file before uploading. It's using jQuery to detect whenever the contents are added or changed, but you can still get files[0].size without using jQuery.
$(document).ready(function() {
$('#openFile').on('change', function(evt) {
console.log(this.files[0].size);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="upload.php" enctype="multipart/form-data" method="POST" id="uploadform">
<input id="openFile" name="img" type="file" />
</form>
Here's a more complete example, some proof of concept code to Drag and Drop files into FormData and upload via POST to a server. It includes a simple check for file size.
I had the same problem and seems like we haven't had an accurate solution. Hope this can help other people.
After take time exploring around, I finally found the answer. This is my code to get file attach with jQuery:
var attach_id = "id_of_attachment_file";
var size = $('#'+attach_id)[0].files[0].size;
alert(size);
This is just the example code for getting the file size. If you want do other stuffs, feel free to change the code to satisfy your needs.
Best solution working on all browsers ;)
function GetFileSize(fileid) {
try {
var fileSize = 0;
// for IE
if(checkIE()) { //we could use this $.browser.msie but since it's deprecated, we'll use this function
// before making an object of ActiveXObject,
// please make sure ActiveX is enabled in your IE browser
var objFSO = new ActiveXObject("Scripting.FileSystemObject");
var filePath = $("#" + fileid)[0].value;
var objFile = objFSO.getFile(filePath);
var fileSize = objFile.size; //size in b
fileSize = fileSize / 1048576; //size in mb
}
// for FF, Safari, Opeara and Others
else {
fileSize = $("#" + fileid)[0].files[0].size //size in b
fileSize = fileSize / 1048576; //size in mb
}
alert("Uploaded File Size is" + fileSize + "MB");
}
catch (e) {
alert("Error is :" + e);
}
}
from http://www.dotnet-tricks.com/Tutorial/jquery/HHLN180712-Get-file-size-before-upload-using-jquery.html
UPDATE :
We'll use this function to check if it's IE browser or not
function checkIE() {
var ua = window.navigator.userAgent;
var msie = ua.indexOf("MSIE ");
if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./)){
// If Internet Explorer, return version number
alert(parseInt(ua.substring(msie + 5, ua.indexOf(".", msie))));
} else {
// If another browser, return 0
alert('otherbrowser');
}
return false;
}
$(document).ready(function() {
$('#openFile').on('change', function(evt) {
console.log(this.files[0].size);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="upload.php" enctype="multipart/form-data" method="POST" id="uploadform">
<input id="openFile" name="img" type="file" />
</form>
Browsers with HTML5 support has files property for input type.
This will of course not work in older IE versions.
var inpFiles = document.getElementById('#fileID');
for (var i = 0; i < inpFiles.files.length; ++i) {
var size = inpFiles.files.item(i).size;
alert("File Size : " + size);
}
Please do not use ActiveX as chances are that it will display a scary warning message in Internet Explorer and scare your users away.
If anyone wants to implement this check, they should only rely on the FileList object available in modern browsers and rely on server side checks only for older browsers (progressive enhancement).
function getFileSize(fileInputElement){
if (!fileInputElement.value ||
typeof fileInputElement.files === 'undefined' ||
typeof fileInputElement.files[0] === 'undefined' ||
typeof fileInputElement.files[0].size !== 'number'
) {
// File size is undefined.
return undefined;
}
return fileInputElement.files[0].size;
}
ucefkh's solution worked best, but because $.browser was deprecated in jQuery 1.91, had to change to use navigator.userAgent:
function IsFileSizeOk(fileid) {
try {
var fileSize = 0;
//for IE
if (navigator.userAgent.match(/msie/i)) {
//before making an object of ActiveXObject,
//please make sure ActiveX is enabled in your IE browser
var objFSO = new ActiveXObject("Scripting.FileSystemObject");
var filePath = $("#" + fileid)[0].value;
var objFile = objFSO.getFile(filePath);
var fileSize = objFile.size; //size in b
fileSize = fileSize / 1048576; //size in mb
}
//for FF, Safari, Opeara and Others
else {
fileSize = $("#" + fileid)[0].files[0].size //size in b
fileSize = fileSize / 1048576; //size in mb
}
return (fileSize < 2.0);
}
catch (e) {
alert("Error is :" + e);
}
}
you need to do an ajax HEAD request to get the filesize. with jquery it's something like this
var req = $.ajax({
type: "HEAD",
url: yoururl,
success: function () {
alert("Size is " + request.getResponseHeader("Content-Length"));
}
});
Get the size of the file by files.item(i).size.
You should try this.
https://www.geeksforgeeks.org/validation-of-file-size-while-uploading-using-javascript-jquery/
You can use PHP filesize function. During upload using ajax, please check the filesize first by making a request an ajax request to php script that checks the filesize and return the value.
You can by using HTML5 File API: http://www.html5rocks.com/en/tutorials/file/dndfiles/
However you should always have a fallback for PHP (or any other backend language you use) for older browsers.
Personally, I would say Web World's answer is the best today, given HTML standards. If you need to support IE < 10, you will need to use some form of ActiveX. I would avoid the recommendations that involve coding against Scripting.FileSystemObject, or instantiating ActiveX directly.
In this case, I have had success using 3rd party JS libraries such as plupload which can be configured to use HTML5 apis or Flash/Silverlight controls to backfill browsers that don't support those. Plupload has a client side API for checking file size that works in IE < 10.
I have one file i.e style.css/any file whose content need to be shifted to another text file which is file.txt. Using ActiveXObject is not working, so could you please provide any other solution.?
Here is my code which I tried.
jQuery(function ($) {
$.get('css/style.css', function (data) {
// alert(data);
writeToFile(data);
});
function writeToFile(content) {
// alert(content);
var fso = new ActiveXObject("Scripting.FileSystemObject");
var fh = fso.OpenTextFile("file.txt", 8);
fh.WriteLine(content);
fh.Close();
}
});
You can try this
window.location = "data:text/html," + yourData
It'll dump the data in the url and force a download of the data.
Hi all, the question Title may be duplicated but the idea is different.
I need to validate file size in html using attribute
like:
<input type="file" id="file" multiple="" data-my-size="123456">
When the user selects file it checks the size with this data-my-size value.
and then it creates a div inside a div with id "file-list" with file name and if it is allowed or not.
for example:
<div id="file-list">
<div> File 123.png is allowed </div>
<div> File 321.png is Not allowed </div>
</div>
and it works with more than One input in the same page
Try this function....
function GetFileSize(fileid) {
try
{
var fileSize = 0;
//for IE
if ($.browser.msie) {
//before making an object of ActiveXObject,
//please make sure ActiveX is enabled in your IE browser
var objFSO = new ActiveXObject("Scripting.FileSystemObject"); var filePath = $("#" + fileid)[0].value;
var objFile = objFSO.getFile(filePath);
var fileSize = objFile.size; //size in kb
fileSize = fileSize / 1048576; //size in mb
}
//for FF, Safari, Opeara and Others
else {
fileSize = $("#" + fileid)[0].files[0].size //size in kb
fileSize = fileSize / 1048576; //size in mb
}
alert("Uploaded File Size is" + fileSize + "MB");
}
catch (e) {
alert("Error is :" + e);
}
Is there any way to find out the file size before uploading the file using AJAX / PHP in change event of input file?
For the HTML bellow
<input type="file" id="myFile" />
try the following:
//binds to onchange event of your input field
$('#myFile').bind('change', function() {
//this.files[0].size gets the size of your file.
alert(this.files[0].size);
});
See following thread:
How to check file input size with jQuery?
<script type="text/javascript">
function AlertFilesize(){
if(window.ActiveXObject){
var fso = new ActiveXObject("Scripting.FileSystemObject");
var filepath = document.getElementById('fileInput').value;
var thefile = fso.getFile(filepath);
var sizeinbytes = thefile.size;
}else{
var sizeinbytes = document.getElementById('fileInput').files[0].size;
}
var fSExt = new Array('Bytes', 'KB', 'MB', 'GB');
fSize = sizeinbytes; i=0;while(fSize>900){fSize/=1024;i++;}
alert((Math.round(fSize*100)/100)+' '+fSExt[i]);
}
</script>
<input id="fileInput" type="file" onchange="AlertFilesize();" />
Work on IE and FF
Here's a simple example of getting the size of a file before uploading. It's using jQuery to detect whenever the contents are added or changed, but you can still get files[0].size without using jQuery.
$(document).ready(function() {
$('#openFile').on('change', function(evt) {
console.log(this.files[0].size);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="upload.php" enctype="multipart/form-data" method="POST" id="uploadform">
<input id="openFile" name="img" type="file" />
</form>
Here's a more complete example, some proof of concept code to Drag and Drop files into FormData and upload via POST to a server. It includes a simple check for file size.
I had the same problem and seems like we haven't had an accurate solution. Hope this can help other people.
After take time exploring around, I finally found the answer. This is my code to get file attach with jQuery:
var attach_id = "id_of_attachment_file";
var size = $('#'+attach_id)[0].files[0].size;
alert(size);
This is just the example code for getting the file size. If you want do other stuffs, feel free to change the code to satisfy your needs.
Best solution working on all browsers ;)
function GetFileSize(fileid) {
try {
var fileSize = 0;
// for IE
if(checkIE()) { //we could use this $.browser.msie but since it's deprecated, we'll use this function
// before making an object of ActiveXObject,
// please make sure ActiveX is enabled in your IE browser
var objFSO = new ActiveXObject("Scripting.FileSystemObject");
var filePath = $("#" + fileid)[0].value;
var objFile = objFSO.getFile(filePath);
var fileSize = objFile.size; //size in b
fileSize = fileSize / 1048576; //size in mb
}
// for FF, Safari, Opeara and Others
else {
fileSize = $("#" + fileid)[0].files[0].size //size in b
fileSize = fileSize / 1048576; //size in mb
}
alert("Uploaded File Size is" + fileSize + "MB");
}
catch (e) {
alert("Error is :" + e);
}
}
from http://www.dotnet-tricks.com/Tutorial/jquery/HHLN180712-Get-file-size-before-upload-using-jquery.html
UPDATE :
We'll use this function to check if it's IE browser or not
function checkIE() {
var ua = window.navigator.userAgent;
var msie = ua.indexOf("MSIE ");
if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./)){
// If Internet Explorer, return version number
alert(parseInt(ua.substring(msie + 5, ua.indexOf(".", msie))));
} else {
// If another browser, return 0
alert('otherbrowser');
}
return false;
}
$(document).ready(function() {
$('#openFile').on('change', function(evt) {
console.log(this.files[0].size);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="upload.php" enctype="multipart/form-data" method="POST" id="uploadform">
<input id="openFile" name="img" type="file" />
</form>
Browsers with HTML5 support has files property for input type.
This will of course not work in older IE versions.
var inpFiles = document.getElementById('#fileID');
for (var i = 0; i < inpFiles.files.length; ++i) {
var size = inpFiles.files.item(i).size;
alert("File Size : " + size);
}
Please do not use ActiveX as chances are that it will display a scary warning message in Internet Explorer and scare your users away.
If anyone wants to implement this check, they should only rely on the FileList object available in modern browsers and rely on server side checks only for older browsers (progressive enhancement).
function getFileSize(fileInputElement){
if (!fileInputElement.value ||
typeof fileInputElement.files === 'undefined' ||
typeof fileInputElement.files[0] === 'undefined' ||
typeof fileInputElement.files[0].size !== 'number'
) {
// File size is undefined.
return undefined;
}
return fileInputElement.files[0].size;
}
ucefkh's solution worked best, but because $.browser was deprecated in jQuery 1.91, had to change to use navigator.userAgent:
function IsFileSizeOk(fileid) {
try {
var fileSize = 0;
//for IE
if (navigator.userAgent.match(/msie/i)) {
//before making an object of ActiveXObject,
//please make sure ActiveX is enabled in your IE browser
var objFSO = new ActiveXObject("Scripting.FileSystemObject");
var filePath = $("#" + fileid)[0].value;
var objFile = objFSO.getFile(filePath);
var fileSize = objFile.size; //size in b
fileSize = fileSize / 1048576; //size in mb
}
//for FF, Safari, Opeara and Others
else {
fileSize = $("#" + fileid)[0].files[0].size //size in b
fileSize = fileSize / 1048576; //size in mb
}
return (fileSize < 2.0);
}
catch (e) {
alert("Error is :" + e);
}
}
you need to do an ajax HEAD request to get the filesize. with jquery it's something like this
var req = $.ajax({
type: "HEAD",
url: yoururl,
success: function () {
alert("Size is " + request.getResponseHeader("Content-Length"));
}
});
Get the size of the file by files.item(i).size.
You should try this.
https://www.geeksforgeeks.org/validation-of-file-size-while-uploading-using-javascript-jquery/
You can use PHP filesize function. During upload using ajax, please check the filesize first by making a request an ajax request to php script that checks the filesize and return the value.
You can by using HTML5 File API: http://www.html5rocks.com/en/tutorials/file/dndfiles/
However you should always have a fallback for PHP (or any other backend language you use) for older browsers.
Personally, I would say Web World's answer is the best today, given HTML standards. If you need to support IE < 10, you will need to use some form of ActiveX. I would avoid the recommendations that involve coding against Scripting.FileSystemObject, or instantiating ActiveX directly.
In this case, I have had success using 3rd party JS libraries such as plupload which can be configured to use HTML5 apis or Flash/Silverlight controls to backfill browsers that don't support those. Plupload has a client side API for checking file size that works in IE < 10.