File Size and Format before uploading - javascript

Is there any way to check for file format and size of the file before uploading it in javascript?

No, that's not possible. You can check for the extension but still it could be wrong because a text file renamed to zip will show you zip as an extension. You need server-side script for that.
Once file is uploaded, you can check its mime-type and size with server-side script.

Assuming you've obtained the fileTobeUploaded object (i don't know how you are doing the upload), with the following you could get the size in bytes.
var reader = new FileReader();
reader.onload = (function(theFile) {
alert(theFile.size);
})(fileTobeUploaded);

I believe you can retrieve size information about the file using FLASH, however to determine the file format, you will most probably need to rely on the file extension... and that's a weak determination with regards to security (malware etc.)

Related

How to load the contents of a local text file by name using Javascript and HTML 5?

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.

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

Extracting files with jszip and saving to local disk using npapi-file-io. Binary file save very slow

I'm using JSZip to open a zip file. Looping and saving each file as a binary file using the npapi-file-io plugin. The problem is; it's very slow. Extracting a zip locally takes a couple of minutes even for a 2mb zip file. If I save the files as text files it's very fast. But they must be saved as binary or they become corrupt. Any ideas? Please tell me I'm doing this wrong or the hard way.
//read contents of zip file
var zip = new JSZip(e.target.result);
$.each(zip.files, function (index, zipEntry) {
var filename = zipEntry.name;
//create directory else create file
var path = getPath(filename);
if (filename.match(/\/$/)) {
//plugin is the embeded npapi-file-io plugin
plugin.createDirectory(path);
} else {
//problem is here
plugin.saveBinaryFile(path, zipEntry.asUint8Array());
//this is faster and works with the txt files but not images ect.
//plugin.saveTextFile(path, zipEntry.data);
}
There is no performant way to send binary data to a plugin; basically to send something using a uint8array will always be very slow because of how npapi works, so you'd be better off if you could send it base64 encoded. What it comes down to is that the only way to really do this in a performant way is likely to create your own plugin.

Storing the image from an HTML input file form locally

I was wondering if it is possible to store the image from
<input type="file" id="image">
locally. Would I have to store the image, or could I simply store the image location?
For context, it's from a form that takes name, address etc from input forms, creates an object, stores it in an array and displays the array.
Contrary to the other answers here, if you're using a modern browser you can get and store quite a bit about the contents of a file <input> using elm.files, FileReader and window.localStorage. You can even tell the browser to save it again (default download behaviour).
It should be noted that doing this does not mean you can set the .value on the <input> node.
Here is an example of what you can do, assuming a file has been chosen.
// From <input> node
var elm = document.getElementById('image'),
img = elm.files[0],
fileName = img.name, // not path
fileSize = img.size; // bytes
// By Parsing File
var reader = new FileReader(),
binary, base64;
reader.addEventListener('loadend', function () {
binary = reader.result; // binary data (stored as string), unsafe for most actions
base64 = btoa(binary); // base64 data, safer but takes up more memory
}, false);
reader.readAsBinaryString(img);
From here you can save in localStorage, create dataURIs etc. For example, Say from fileName we know the image is a .jpg, then you could display it by setting an <img>'s src to "data:image/jpeg;base64," + base64.
Note that any modification of this data will not have any effect on the original file chosen.
No way. But if you could that would raise serious security issues.
If you try to get value of your file input e.g.:
document.getElementById('image').value
the value would be "C:\fakepath\somefile.txt"
No. Since storing a file or accessing a file on the local OS would violate the permissions of the browser. So your scripts cannot access the content unless it has been uploaded to the server. Also different browsers handle the path of the file that has been selected in different ways. So you encounter a number of problems there.
That said, there are some ways to get around this that I will not discuss. Simply put, the image should be uploaded to the server in some fashion and then your scripts can reference the path or the image itself from the path that it was uploaded to.
If you want to get the file name, or even display the image, you can do that using the File API (on browsers that support it). The path is not available for security reasons.

Is there a way to let a user view an image they are about to upload client side before uploading to the server?

When a user is uploading an image, is there a way I can load the image client side and show it to them first, before uploading it to the server? Preferably using javascript/jquery only, but using flash would be acceptable too.
It is possible with the new FileReader interface defined in HTML5 and works on Firefox currently.
A file input has an associated files property which tracks the list of files currently selected for that input. To display a file from this list, create a new FileReader object, initialize its onload event handler, and read the file as a data URL.
// get the first file, foo is a file input field
var file = document.getElementById('foo').files[0];
// setup the reader and the load complete callback
var reader = new FileReader();
reader.onload = function(e) {
var image = new Image();
// string representing the image
image.src = e.target.result;
document.body.appendChild(image);
};
// read the file as a data url
reader.readAsDataURL(file);
Once the file is loaded, you will have access to its contents in a data url scheme, for instance:
data:image/jpeg;base64,...aqHI7sNyPGFjdtQvFr/2Q==
Create a new Image and set its src attribute to this data string.
See a working example here. Firefox only.
You can't really do this cross-browser in JavaScript alone due security restrictions that are in place, there are a few flash versions available though, here's one example (the free version does what you're after).
There are probably more free flash versions out there as well.
Since HTML 5 those things are possible, thanks to the File Object, File Reader and the ´files´ property of the input element.
See here for more information: http://demos.hacks.mozilla.org/openweb/ & http://hacks.mozilla.org/2009/12/file-drag-and-drop-in-firefox-3-6/.
Example (only for demonstration, requires FF 3.5+):
See here: http://gist.github.com/536024
In case you wonder, File.url is brand new, with it you dont anymore need to read the whole file into the memory, and assign the whole DataUrl (data:image/src,base64;DF15EDFE86..) to the src property.
Well, the <img> tag needs a path to the image. That path can be to something on the web, or to a local file. So far, so good. The trick is, how do you tell your javascript the path on the local system, so it can set the IMG SRC attribute.
The path of the file <input> tag is unavailable to javascript (as a security precaution --- you don't want a want page upload files from you system behind your back).
On the other hand, if you can get your users to enter a correct file path name into a text <input> field, then it should be possible.

Categories