dataURL does not work for <a> - javascript

update: Finally I find out the reason myself, the reason is: actually I used Angular's ng-href at the same time, which prefix a unsafe to the data url, I have to config the compiler service to waive that restriction like:
.config( [
'$compileProvider',
function( $compileProvider )
{
$compileProvider.aHrefSanitizationWhitelist(/^\s*(https?|ftp|mailto|chrome-extension):/);
// Angular before v1.2 uses $compileProvider.urlSanitizationWhitelist(...)
}
])
Which talks about here:
Angular changes urls to "unsafe:" in extension page
All:
What I want to do is read in a image as dataURL and give it to a tag as download:
<input type='file' name='doc' />
Download
<script>
var fileOBJ = $("input")[0]
.files[0];
var reader = new FileReader();
reader.onload = function(e){
$("a")[0].href=e.target.result;
}
reader.onerror = function(err){
console.log(err);
}
reader.readAsDataURL(fileOBJ);
</script>
The download always failed.
But if I use a <img> instead of <a>, then the image can shown up. I do not know what is wrong with the <a> link

Specify the atrribute download on the link. Like this:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='file' name='doc' />
<a download="filename" href="#">Download</a>
<script>
$("input").change(function() {
var fileOBJ = $("input")[0]
.files[0];
var reader = new FileReader();
reader.onload = function(e) {
$("a")[0].href = e.target.result;
// if you want to change the download filename
// $($("a")[0]).attr("download", "some other filename");
}
reader.onerror = function(err) {
console.log(err);
}
reader.readAsDataURL(fileOBJ);
})
</script>

You try to call readAsDataURL when there is any file selected, what throws an error. Use this method after you select some file.
var reader = new FileReader();
reader.onload = function(e){
$("a")[0].href = e.target.result;
};
reader.onerror = function(err){
console.log(err);
};
$('#inpFile').on('change',function(){
reader.readAsDataURL(this.files[0]);
});

Related

Turning a html File (API Type) instance into a string?

With the HTML File API we can get a file selected via an <input type="file"> element with var file = evt.target.files[0];.
How do we get the file content as a string (Something like var content = file.toString().
I currently have this code which gets triggered by the input element.onchange event:
input.onchange = function handleFileSelect(evt) {
var file = evt.target.files[0];
var reader = new FileReader();
console.log("RAW FILE: ", file);
var string = reader.readAsText(file);
console.log("FILE CONTENT: ", string);
}
When I select a file I try to log the contents this happens:
RAW FILE: File
bundle.js:5293 FILE CONTENT: undefined
Thoughts?
Turns out a file cannot just be read synchronously like this:
var reader = new FileReader();
content = reader.readAsText(file);
Before we can read the file we first have to attach to the onload event on the file reader.
reader.onload = (e) => {
let content = e.target.result;
console.log("FILE CONTENT: ", content);
}
The trigger the file read:
reader.readAsText(file);
The content will now contain the file content.

Reading uploaded text file contents in variable

I want to read string from text file and save it in variable . What I did:
HTML:
<div>
Select a text file:
<input type="file" id="fileInput">
</div>
<pre id="fileDisplayArea"><pre>
JS:
window.onload = function() {
var fileInput = document.getElementById('fileInput');
var fileDisplayArea = document.getElementById('fileDisplayArea');
var newString;
fileInput.addEventListener('change', function(e) {
var file = fileInput.files[0];
var textType = /text.*/;
if (file.type.match(textType)) {
var reader = new FileReader();
reader.onload = function(e) {
fileDisplayArea.innerText = reader.result;
}
newString=reader.result; //SAVE RESULT
alert(newString);
reader.readAsText(file);
} else {
fileDisplayArea.innerText = "File not supported!"
}
});
}
I want to save text from file and alert it. But it doesnt work.
I did it:
var tfile;
var reader = new FileReader();
function rdfile(files)
{
tfile = files[0];
reader.readAsText(tfile, 'CP1251');
reader.onload = function(e)
{
str = e.target.result;
alert(str);
};
}
But it doesnt work too. I alert many different symbols but not my text.
Look at your code from your first attempt:
newString=reader.result; //SAVE RESULT
alert(newString);
reader.readAsText(file);
Get the result
Alert it
Do the thing that generates the result
You have to read the file before you can look at the text you get from reading it!
Move steps 1 and 2 in to the onload event handler you already have.
Now look at your second attempt. You never call rdfile and you never call readAsText.

HTML5 FileReader, read from local file

I want to read a local binary file. So, I do this
var file = new File([""], url);
var reader = new FileReader();
reader.onload = function () {
parse(reader.result);
}
reader.readAsArrayBuffer(file);
where url is a filepath like url="c:\temp\myfile.bin"
I don't have any errors, but something is wrong, because all data from my app disappear. What could be wrong ? Any ideas ?
Thanks!
I guess you have to use input type="file" for security reasons.
Here's a working example. For convenience it shows the opened file in the same browser window.
<html>
<body>
<script>
function readFile() {
var reader = new FileReader();
file = document.getElementById("uploadText").files[0];
reader.onload = function (ev) {
document.getElementById("obj").data = ev.target.result;
// parse(ev.target.result);
};
reader.readAsDataURL(file);
// reader.readAsArrayBuffer(file);
};
</script>
<div>
<input id="uploadText" type="file" onchange="readFile();" />
</div>
<object id="obj" data="" />
</body>
</html>

Trouble uploading binary files using JavaScript FileReader API

New to javascript, having trouble figuring this out, help!
I am trying to use the Javascript FileReader API to read files to upload to a server. So far, it works great for text files.
When I try to upload binary files, such as image/.doc, the files seem to be corrupted, and do not open.
Using dojo on the client side, and java on the server side, with dwr to handle remote method calls. Code :
Using a html file input, so a user can select multiple files to upload at once :
<input type="file" id="fileInput" multiple>
And the javascript code which reads the file content:
uploadFiles: function(eve) {
var fileContent = null;
for(var i = 0; i < this.filesToBeUploaded.length; i++){
var reader = new FileReader();
reader.onload = (function(fileToBeUploaded) {
return function(e) {
fileContent = e.target.result;
// fileContent object contains the content of the read file
};
})(this.filesToBeUploaded[i]);
reader.readAsBinaryString(this.filesToBeUploaded[i]);
}
}
The fileContent object will be sent as a parameter to a java method, which will write the file.
public boolean uploadFile(String fileName, String fileContent) {
try {
File file = new File("/home/user/files/" + fileName);
FileOutputStream outputStream = new FileOutputStream(file);
outputStream.write(fileContent.getBytes());
outputStream.close();
} catch (FileNotFoundException ex) {
logger.error("Error uploading files: ", ex);
return false;
} catch (IOException ioe) {
logger.error("Error uploading files: ", ioe);
return false;
}
return true;
}
I have read some answers suggesting the use of xhr and servlets to achieve this.
Is there a way to use FileReader, so that it can read files of any type (text, image, excel etc.) ?
I have tried using reader.readAsBinaryString() and reader.readAsDataUrl() (Decoded the base64 fileContent before writing to a file), but they did not seem to work.
PS :
1. Also tried reader.readAsArrayBuffer(), the resultant ArrayBuffer object shows some byteLength, but no content, and when this is passed to the server, all I see is {}.
This bit of code is intended to work on only newer versions of browsers..
Thanks N.M! So, it looks like ArrayBuffer objects cannot be used directly, and a DataView must be created in order to use them. Below is what worked -
uploadFiles: function(eve) {
var fileContent = null;
for(var i = 0; i < this.filesToBeUploaded.length; i++){
var reader = new FileReader();
reader.onload = (function(fileToBeUploaded) {
return function(e) {
fileContent = e.target.result;
var int8View = new Int8Array(fileContent);
// now int8View object has the content of the read file!
};
})(this.filesToBeUploaded[i]);
reader.readAsArrayBuffer(this.filesToBeUploaded[i]);
}
}
Refer N.M 's comments to the question for links to the relevant pages.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Typed_arrays
example
<html>
<head>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.11.3/themes/smoothness/jquery-ui.css">
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script src="http://code.jquery.com/ui/1.11.3/jquery-ui.js"></script>
</head>
<body>
<script>
function PreviewImage() {
var oFReader = new FileReader();
oFReader.readAsDataURL(document.getElementById("uploadImage").files[0]);
oFReader.onload = function (oFREvent) {
var sizef = document.getElementById('uploadImage').files[0].size;
document.getElementById("uploadPreview").src = oFREvent.target.result;
document.getElementById("uploadImageValue").value = oFREvent.target.result;
};
};
jQuery(document).ready(function(){
$('#viewSource').click(function ()
{
var imgUrl = $('#uploadImageValue').val();
alert(imgUrl);
//here ajax
});
});
</script>
<div>
<input type="hidden" id="uploadImageValue" name="uploadImageValue" value="" />
<img id="uploadPreview" style="width: 150px; height: 150px;" /><br />
<input id="uploadImage" style="width:120px" type="file" size="10" accept="image/jpeg,image/gif, image/png" name="myPhoto" onchange="PreviewImage();" />
</div>
Source file
</body>
</html>

downloading a javascript blob variable as mhtml

I'm writing a google chrome extension that uses
chrome.pageCapture.saveAsMHTML(object details, function callback)
function callback (blob mhtmlData) {...};
http://code.google.com/chrome/extensions/dev/pageCapture.html
which basically stores a blob representation of an mhtml page into a variable.
Now I want to let the user download this blob variable as an mhtml file..
I tried this but is gives me a 200kb file filled with random characters.
chrome.pageCapture.saveAsMHTML({tabId: sender.tab.id}, function callback(mhtml){
var reader = new FileReader();
reader.readAsDataURL(mhtml);
reader.onload = function(e) {
window.open(e.target.result);
}
});
Following is some code that I put in a page actions popup. I left the stuff that I didnt use but commented it out for reference.
EDIT:
Using the library from https://github.com/eligrey/FileSaver.js it was easy, maybe you could look at that to see what their doing.
popup.html
<html>
<head>
<script xmlns="http://www.w3.org/1999/xhtml" type="application/ecmascript" async="" src="https://raw.github.com/eligrey/FileSaver.js/master/FileSaver.min.js"></script>
<script>
function onLoad(){
var downloadLink = document.querySelector("#MHTML");
var oFReader = new FileReader();
oFReader.onload = function (oFREvent) {
// None of the following worked
//window.open('data:application/octet-stream;'+oFREvent.target.result.slice(5));
//window.open('data:application/message/rfc822;'+oFREvent.target.result.slice(5));
//window.open(oFREvent.target.result);
};
chrome.tabs.getSelected(null, function(tab) {
chrome.pageCapture.saveAsMHTML({tabId: tab.id}, function (mhtml){
/// Works but requires user input
//downloadLink.setAttribute('download',tab.title+'.mhtml');
//downloadLink.setAttribute('href',window.webkitURL.createObjectURL(mhtml));
///Works but awful filename without extension
//window.open(window.webkitURL.createObjectURL(mhtml));
///Doesnt work
//oFReader.readAsDataURL(mhtml);
///Using https://github.com/eligrey/FileSaver.js , works great
saveAs(mhtml, tab.title+'.mhtml');
})
});
}
</script>
</head>
<body onload="onLoad();" style="width: 400px">
<a id="MHTML" href="#">Download Page As MHTML</a>
</body>
</html>
In case you want to give the file a name you could use an anchor element and set the name of the download attribute programmatically:
var reader = new FileReader();
reader.readAsDataURL(mhtml);
reader.onloadend = function(e) {
const dataUrl = e.target.result;
const a = document.createElement('a');
a.href = dataUrl;
a.download = fileName;
a.click();
}

Categories

Resources