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
Related
Working in Chrome, loading a local html or JS file.
I found many examples of how to load a file that is selected using the Choose File input.
However, didn't figure out how to do it given a file name without using the Choose File input.
The Choose File input returns a File object.
How to create the File object without the Choose File input?
From the File API:
new File(
Array parts,
String filename,
BlobPropertyBag properties
);
But didn't figure out what the parts and properties would be.
Edit: Use case:
I have code coverage results generated as part of a test suite. It is stored as JSON (which is easy to read), but I need to display it with the source code.
So the feature is to load the source code and JSON data, and render them together on a web page using HTML and Javascript.
The file would be opened from the browser and lives on the local machine. There is no server.
The browser cannot load arbitrary files by name from your filesystem without special extensions or other shenanigans. This is a security policy to prevent random web sites from reading files from your hard disk as you browse the internet.
If you're down to do something special like if you want to write a chrome app, you could get access to some nice APIs for accessing the filesystem:
https://developer.chrome.com/apps/fileSystem
The File constructor doesn't read a file from the harddrive, but rater make a virtual file, consider this:
var file = new File(["some", "content"], "/tmp/my-name.txt");
var reader = new FileReader();
reader.onload = function() {
console.log(reader.result); // somecontent
};
No file will be read or stored on the clients machine.
If you are talking about creating files in nodejs then you should take a look at fs.
For security reasons all browsers don't support predefined values on file fields so the answer is you can't.
We are developing an app that is to download files from HTTP URLs, the extensions/file types of which we will not know until runtime. We've been following this tutorial as a starting point, but since we aren't dealing with images, it hasn't helped us.
The issue is that the code in the tutorial will get you a Blob object and I can't find any code that will allow us to either:
Convert the Blob to a byte array.
Save the Blob straight to the file system.
The ultimate goal is to seamlessly save the file at the given URL to the file system and launch it with the default application, or to just launch it from the URL directly (without the save prompt you get if you just call Windows.System.Launcher.launchUriAsync(uri);).
Any insight anyone might have is greatly appreciated.
Regarding downloading content into byte array:
Using WinJS.xhr with the responseType option as 'arraybuffer' will return the contents in ArrayBuffer. A javascript typed array can be instantiated from the ArrayBuffer for example UInt8Array. This way contents can be read into byte array. code should look something like this:
// todo add other options reqd
var options = { url: url, responseType: 'arraybuffer' };
WinJS.xhr(options).then(function onxhr(ab)
{
var bytes = new Uint8Array(ab, 0, ab.byteLength);
}, function onerror()
{
// handle error
});
Once you take care of permissions to save the file to file system either by user explicitly picking the save file location using SaveFilePicker or pick folder using folder picker - file can be saved on local file system. Also, file can be saved to app data folder.
AFAIK, html/js/css files from local file system or the app data cannot be loaded for security reasons. Although DOM can be manipulated under constraints, to add content. I am not sure of your application requirements. You might need to consider alternatives instead of launching downloaded html files.
My website require user upload their xml file with specify format.
So I want do a syntax and format check on client side, and help them fix those error before upload to server. (I do not require change the real local file on hard drive, only need change the data send to server)
I currently use:
var reader = new FileReader();
reader.onload = function(e) {
var xml = e.target.result;
// I help them correct xml here, this will involve lots of interaction with user,
// so I want it only happen on client side
var correctXML = fixSyntaxAndFormat(xml);
$.post('/foo/bar', {xml: correctXML});
}
reader.readAsText(evt.target.files[0]);
This code works, except it send xml in post data instead of a real uploaded file.
Because I want monitor file upload progress and save other file information, so I hope can have something like: oldfile.content = correctXML
then I can just submit that form which contain my <input type="file"/>.
Is this possible to do ? Or is there a "correct" way to do this?
Thanks
Update
Thanks for austincheney's example, I end up with create new Blob() and use this replace the original file. Seems work fine.
Yes this is entirely possible, and it is typically used to assist with drag and drop file operations. For instance if you want users to be able to drop files onto a textarea you can make the textarea a drop zone where the path the files is fed silently to the input type file element. I do this on my own site.
Checkout the function pd.file and pd.filedrop in http://prettydiff.com/pd.js and demo the result on my tool at http://prettydiff.com/
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
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.