How do I open a file stream in javascript? - javascript

To give a concrete example of what I mean:
Imagine I have an HTML page that looks like this
<div>
<div id="filecontents">
<!-- some html file contents -->
</div>
<input type="button" />
</div>
I would like to be able to click on the button, and it bring me up with a "Open or save file" dialog box.
Is this even possible?
The objective of this is, is for me to be able to open up some html, text, or a CSV using the contents of a div as a data source for the file.

You can do this using the HTML5 FileSystem APIs. A couple tutorials here:
Reading local files in JavaScript
Exploring the FileSystem APIs
Browser support is weak right now, but my guess is that it's the closest to what you want.

doesn't <input type="file" /> do that exact thing?

I don't understand all these answers that say this is not possible without a plugin. I would say it absolutely is possible with standard web technologies, but requires user interaction and server interaction. Of course you can't go reading or writing whatever you want on a user's computer from the web, but you can ask a user for a file (open), and give a user a file (save).
To open a file with JavaScript, use a <input type="file" />. If you want, you can use JavaScript to display the open dialog by calling the click() method on the file input (the DOM method, not the jQuery method). In the onchange handler, submit the form, read the uploaded file, and write the contents to your page.
To save a file with JavaScript, send the contents of the file to the server, prepare the file, and stream it back to the client with a content-disposition header of attachment; filename="file.txt". This header causes the file to be downloaded and saved the user's pc rather than displayed in the browser.
Do that and you've officially written your first cloud computing app!

<input type="file" /> will allow you to upload a file to the server, but you have no direct access to that file, or to the local file system, from javascript - this is a security feature.
If you want to alter the page somehow based on the contents of the file, you will have to do a round-trip: upload the file to the server, then render a new page with the changes you want, and send it back to the client.
I have seen some file-stream-like code written for javascript (i.e., a flash implementation), but they must "load" files via an ajax request and then read the data as a javascript string.

You cannot access the local filesystem from javascript because of security reasons. You can, however, receive files via drag and drop in modern browsers or use an java applet that communicates with your javascript.
EDIT: forgot about the new HTML5 file api linked by Michael Mior. Go with his answer, he's the man. If you need cross browser support, go with the java applet, its painful but works.

Not with pure JavaScript. You can't open a file dialog to save part of the HTML, for example. Even if you could, there is no way to open a local file with JavaScript for security reasons (otherwise, malicious web sites could steal all your data).
But every browser allows to write plugins (most of them are written in JavaScript), so you could try this approach.

Use this script and put it in the button that the file browser should display.
function handleFileSelect(evt) {
var files = evt.target.files;
for (var i = 0, f; f = files[i]; i++) {
if (!f.type.match('image.*')) {
continue;
}
var reader = new FileReader();
reader.onload = (function(theFile) {
return function(e) {
var span = document.createElement('span');
span.innerHTML = ['<img class="thumb" src="', e.target.result, '"
title = "', escape(theFile.name), '" / > '].join('
');
document.getElementById('list').insertBefore(span, null);
};
})(f); reader.readAsDataURL(f);
}
}
document.getElementById('files').addEventListener('change', handleFileSelect, false);

Related

In JavaScript, are there any security issues associated with FileReader?

Consider the following piece of code:
(Partial) HTML:
<input type="file" accept=".txt" id="theFile" class="button" />
(Partial) JavaScript:
$('#theFile').on('change', function(e){
readFile(this.files[0], function(e) {
var text = e.target.result;
})
})
function readFile(file, callback){
var reader = new FileReader();
reader.onload = callback
reader.readAsText(file);
}
My question is, is there any security risk involved in the use of FileReader, particularly in this case, when deployed with readAsText? For example, what happens if the file chosen is not a .txt but something else? Is it possible for a malicious user to attack the hosting website in some way?
If it's relevant for the purposes of the question, the full code simply retrieves a text from a .txt file and prints parts of it on screen.
Any other detail or information required, I'd be happy to provide.
Yes, you are fine here there is no security issues.
The code is been executed in the users browser not the server, so even if it was malicious, they would only be infecting themselves.
The code above is only reading the file as text, so even if it was malicious it won't be getting executed.
Were you do need to be careful when creating a website, is if you allow a user to upload malicious files, and then somehow allow them to execute them server side. An example would be were a PHP website didn't have correct security, you allowed them to upload a bad PHP file and this directory was available via the website, the PHP file could then be executed server side by them just putting www.mywebsite.com/upload/danger.php into there browser.

Upload file inside chrome extension

I need to add a browse button inside my Chrome extension. Users click it and choose a file. I then want to retrieve the file contents (bytes) and do some work on it.
I don't want to have to submit the file to a remote server and then get the response (if that's even doable from inside a Chrome extension), it should be all client-side.
Is this doable inside Chrome extensions?
You should be looking at the FileReader API.
The FileReader object lets web applications asynchronously read the contents of files (or raw data buffers) stored on the user's computer, using File or Blob objects to specify the file or data to read.
A very good basic example of using this interface is in this question.
A minimal example: suppose that you have an <input type="file" id="file"> with a text file selected.
var file = document.getElementById("file").files[0];
var reader = new FileReader();
reader.onload = function(e){
console.log(e.target.result);
}
reader.readAsText(file);
If you need methods other than reading as text (i.e. binary data), see the docs.
Also, this is a good overview: Using files from web applications
Regarding your question it is totally feasible to load and process a file within an extension. I implemented it using message passing https://developer.chrome.com/docs/extensions/mv3/messaging/.
Here is an example of how you can implement it, in my case I used the input file to load an excel. This is my public repo.
https://github.com/juanmachuca95/gomeetplus

How to load images from the local machine to JS object avoiding loading to the server

I want to load an image file from the computer directly to any js object without using any server-side component. For example, I want to select a picture from the local machine and display it on a webpage. Is there a way to avoid file upload to the server?
In fact I want to write a kind of multiple image loader, but before loading to the server I want to rotate some images, create an xml-file with some data like user id, image file names list and to zip all images and this xml and then send it to the server. How can I do that on the client side?
There is a way with HTML5, but it requires the user to have dropped the file into a drop target or used a <input type="file"/> box, since otherwise it would be a security issue.
Using the File API you can read files, and specifically you can use the FileReader.readAsDataURL method to set the content as a data: URL for the image tag.
Here's an example:
$('#f').on('change', function(ev) {
var f = ev.target.files[0];
var fr = new FileReader();
fr.onload = function(ev2) {
console.dir(ev2);
$('#i').attr('src', ev2.target.result);
};
fr.readAsDataURL(f);
});​
http://jsfiddle.net/alnitak/Qszjg/
Using the new File APIs, it is possible to access content from the local disk.
You put a traditional <input type="file"> upload field on your page, and handle the onchange event.
MDN has a good writeup with all of the details.
Your event handler gets a FileList containing Files. From there, you can call FileReader.readAsDataURL(File) to fetch the content of the image and then pass that data URL to an <img> or a <canvas> to do rotation.
You can use createObjectURL method of the window.URL object, this doesn't have much browser support though
http://jsfiddle.net/LvAqp/ only works in chrome and firefox

loading an image through javascript

is there a way to load the full binary of an image in javascript?
what i want to do is to allow the user to preview an image before uploading it.
ie the user selects an image on his local drive (C:\image.jpg) , view it, and decides to upload or cancel.
i tried to set the source to the image path, but it didn't work since it is outside the webapplication project folder.
any help?
thx for your posts, but i ended up creating a temp folder on the server that stores the uploaded image using ajax. and when the user saves the data, the image is moved to another location, and the temp folder is deleted.
You can do something like this:
<img id="preview" src="" style="display:none;" />
<form>
....
<input type="file" id="file" />
....
</form>
<script type="text/javascript">
var file = document.getElementById("file");
var img = document.getElementById("preview");
file.onchange = function(){
img.src = file.value;
img.style.display = 'block';
};
</script>
There is no easy way, what You could do:
Preload image with some ajax file uploader to temp area and then let user decide
Use some third party written solution (f.ex. some flash component)
Here there is also similar question:
is it possible to preview local images before uploading them via a form?
You need server cooperation to access the image binary data. You won't be able to use the "Upload Form" to access the file info without uploading it to a server.
You could however do something like tell the user to paste the source binary data of the image in a textarea or something, then you can use JavaScript to load that binary data and display the actual image.
This is available in some browsers via the HTML5 file access API. Here is the Firefox documentation for file access.
As answered several times, you can't do this with plain HTML/JavaScript due to security restrictions. You need to send the image anyway. You can however handle this using a Java Applet since it runs entirely at the client machine and offers more control than HTML/JS. There are several free and ready-to-use ones. JumpLoader looks good and some major sites also uses it. With Flash it should also be possible, but I am not sure which ones offers this functionality. Check/tryout some Flash Multi File Uploaders.

How to open a text file using Javascript from Adobe Indesign CS4?

How can I open a text file, read the contents, and then insert the contents into a document in InDesign?
Here's an example of reading a file from InDesign. If you want to write to a file as well, you will need to open the file in write mode w instead.
// Choose the file from a dialog
var file = File.openDialog();
// Or use a hard coded path to the file
// var file = File("~/Desktop/hello world.txt");
// Open the file for reading
file.open("r");
// Get the first text frame of the currently active document
var doc = app.activeDocument;
var firstTextframe = doc.pages[0].textFrames[0];
// Add the contents of the file to the text frame
firstTextframe.contents += file.read();
Here is a link to the File object's documentation online. You can also find the rest of InDesign's scripting DOM documentation here.
This is the pdf for InDesign JavaScript scripting. There's a few mentions of a File object in there, but it's not documented.
http://www.adobe.com/products/indesign/scripting/pdfs/InDesignCS4_ScriptingGuide_JS.pdf
That's because the core utilities for all CS5 products are documented here
https://www.adobe.com/content/dam/Adobe/en/devnet/indesign/cs55-docs/InDesignScripting/InDesign-ScriptingTutorial.pdf
or the general documentation:
http://www.adobe.com/content/dam/Adobe/en/devnet/scripting/pdfs/javascript_tools_guide.pdf
Look for: File System Access
Thanks for the pointer to the various PDFs.
The response to this question is in the execute() command.
fileObj.execute()
Javascript does not allow access to your computer's operating system, files or directories for security reasons, therefore there is no way to access the text file directly using Javascript.
Usually a server-side technology such as PHP, Adobe Coldfusion, Java or .NET (for example) is used to upload the file via a HTML form submission, read it and do whatever it needs to do.
I hope that helps.

Categories