Html file upload preview by Javascript - javascript

I want to show a PREVIEW kind of thing for an post , so took details by JS
but problem comes when it comes to <input type="file" , it's not giving full path to the file
Ex:
if I do
$("#image").val();
it only give "Sunset.jpg" not C:\Documents and Settings\All Users....\Sunset.jpg
any idea how to get that detail value?

Although, as others have already pointed out, you cannot learn the full path to the file in JavaScript, perhaps a completely different approach to the problem might still work for you.
You could upload the photo automatically as soon as the visitor has picked it (the behavior you see in GMail, among other applications), so it's residing on your server even as the visitor continues interacting with your page. At that point, showing a preview is as simple as serving one yourself from your own (now server-side) copy of the image.

This if for security reasons, so you cannot read files from the users system using JavaScript.
If you happen find a workaround, there will probably be security patches released by browser vendors sooner rather than later. I know because in earlier versions if IE, it was possible to read the full path and hence display a preview, at least if the file was an image. I used that in a CMS UI, but of course that nifty feature was ruined by an IE service release :-/
In general the file upload control is somewhat of a "black box" for security reasons. You have only very limited access to scripting and styling it. This is so you can't snoop or upload files without the user knowing, or so you cannot trick the user into uploading files with a deceptive interface.

This is now possible as of Firefox 3.6
https://developer.mozilla.org/en/DOM/FileList
Though the code they show does not seem to work in Chrome, so I'm guessing even the HTML5 JavaScript API for things like this has yet to be standardized.

This is a security feature. You cannot change or get the entire path in secure browsers, so what you want to do, cannot be done. If you use something like Flash, Silverlight or Java, then it should be relatively easy.

As far as I know, there is no way to do what you want to do in javascript. Its a pretty big security issue - having filesystem access in a browser.
There are a few browser plugins (java/flash/gears) that may allow you to do this sort of thing. I know with gears you can get the user to select a file - and open it to read the content using JS.

Related

Issues with either how I'm downloading mobileconfig files (JavaScript below) or how iOS is dealing with it (not sure)

So I created something that allows people to create and download the created .mobileconfig file without the need of a mac (because AC2 is only on macOS) and it's a lot faster to just do it on device. Issue is that when people are downloading it, it prompts as "Do you want to download (filename.mobileconfig) rather than the usual "This website is trying to download a config profile. Do you want to allow this?". This introduces an additional few steps rather than the "click allow, check in settings, and install" option, which is what I'm going for.
I know that it will prompt the correct way if the URL points to the mobileconfig file, except that requires the .mobileconfig file to be stored on the server hosting my site, which I want to avoid if possible, and stick to just HTMl and JavaScript if possible.
This is the JavaScript that's "downloading" the file:
function download(filename, text) {
var element = document.createElement('a');
element.setAttribute('href', 'data:text/xml;charset=UTF-8,' + encodeURIComponent(text));
element.setAttribute('download', filename);
element.style.display = 'none';
document.body.appendChild(element);
element.click();
document.body.removeChild(element);
}
document.getElementById("DownloadProfileBTN").addEventListener("click", function(){
var text = document.getElementById("generated_profile_content").textContent;
var filename = "config.mobileconfig";
download(filename, text);
});
You probably cannot control this.
I have tested this extensively in the four major browsers on iOS, MacOS, and Windows (no Android, and no Windows phones). As of Q1 2022, most major mobile browsers still have embarrassingly bad UX for saving files to disk after they have been transferred to the browser using javascript. One notable exception is Safari on iOS, which has a unique (and pleasant) UI download prompt.
Most other mobile browsers have only one path: attempt to render the transferred file in the browser viewport, and rely on the user to long-press on the visible render and choose "Save As...". This is true whether the file is something most browsers can natively render (i.e. images), or is some complex format like an Office document. Edge has a cool footer with a Download button, but when I was doing my research, it literally never worked. (Microsoft has spent >20 years mastering the art of building terrible web browsers.)
Desktop browsers behave much better across the board: the <a download="filename" ...> approach in your sample gives a seamless instant-download experience in the major browsers. You can programmatically create that link, click it, then remove it from the DOM after a brief delay, and the file will immediately materialize in the user's normal downloads folder.
IIRC, this situation is different if you don't use javascript to manage the download. That is: just have an anchor whose href points to a URL that will respond with a Content-Disposition: attachment header. This is vastly simpler for the front-end, but there are other reasons people don't use this approach. If that's your situation, you may be stuck.
None of this is unique to .mobileconfig files. It's been a long time since I read up on those, but I seem to recall that mobile platforms that consume that type have special handling -- but again, only when it's a direct download rather than being transferred via JS.
Note that this doesn't actually have anything to do with the transfer itself. These troubles flow from the fact that after your JS has transferred the data, it still has to do something to instruct the browser to save the data as a file on disk. The transfer itself is unremarkable and creates no problems, but is pointless if you don't then save it. You don't have many options for writing the file to disk. That feature space is still pretty crappy, I suspect because there are so many extremely important security implications of giving random webpages the power to create local files.
Another fun challenge is that feature-detection will not work here. The basic tools for saving a file technically do exist in all the major browsers (FileReader, ObjectURLs, etc), they all just work differently (and badly). (I think this is Goodhart's Law at work.) Edge has a proprietary msSaveBlob, but like I said, their footer button thing still seems pretty shoddy.
One alternative I have not had an opportunity to test is to use a WebWorker to save the file. IIRC, WebWorkers have the ability to write files to disk, and I was hopeful that it might work the same way in all the browsers. But my project timeline did not have room to spend a day or two experimenting.

Paste image to a web page

I did some research for a wysiwyg editor and found ckeditor that seems to be nice however I need to be able to copy/paste an image to the editor.
I found this web site that do exactly what I need http://pasteboard.co/ so its possible however I cannot find how it's done.
Do you have any ideas or solutions?
I would prefer a solution in pure html5/javascript and avoid any plugin but a silverlight or flash is acceptable too.
There are two ways you can handle this, the easy way, and the hard way.
The Easy Way:
Utilize the Clipboard API. This is an "HTML5" API, but it is only properly supported in Chrome. This will allow you to access a pasted image, from your clipboard, as a Blob. You can then send this Blob to your server via an XHR2 request.
The Hard Way:
Unfortunately, this is what you must do for all browsers other than Chrome, and it's not pretty. It involves you creating a hidden content-editable DIV inside of a "paste target element". This will receive the pasted image. You will then need to draw the image onto a <canvas> which will then need to be converted to a Blob. But wait, it gets better. You may also need to proxy cross-domain images (server-side) in some cases (possibly many cases). This may be required if the server hosting the image does not permit CORS requests on the images they host. You can read more about this situation in this MDN article.
A javascript-based uploader I maintain, Fine Uploader, already supports uploading images via paste, but in Chrome only at this time. I figured I would go through the hassle of implementing this in non-Clipboard API browsers if I received enough requests. Quite frankly, though, since handling non-CORS-enabled images in browsers that do not implement the Clipboard API requires proxying the image server-side, it hardly seems like its worth the effort (unless, of course, my user base tells me that they want it).
Hope this helps.

How can I analyze a file about to be uploaded before it's actually uploaded?

We are currently planning a website on which people can upload movies. When looking at YouTube you notice that some movies are uploaded twice or more times (by different users). To scale our application we're thinking about the following idea:
User selects movie file to be uploaded
A JavaScript will get the SHA256 hash from the file (it's more accurate then the MD5 hash) before it get's uploaded
The website will check if the hash already exists
If the hash doesn't exist, the file will be uploaded
If the hash does exist a message will be prompted or a reference to the already existing version on the server will be created. This without the video being uploaded.
Q: How do we analyze a file with JavaScript in order to get the SHA256 hash, and is SHA256 good enough or should we consider SHA512 (or another algorithm)?
Use the HTML5 File API to read the file: http://www.html5rocks.com/en/tutorials/file/dndfiles. Here is a JS code for calculating SHA-256: http://www.webtoolkit.info/javascript-sha256.html
I must add that I never tried this, but it seems to be possible. Alxandr is right, this would take very long for large videos, but you may try to use the WebWorker API in order not to freeze the browser: http://html5rocks.com/en/tutorials/workers/basics
Putting files aside for now, if the question is actually whether it's possible to get a SHA-256 hashes in JavaScript, the answer is yes. You can either reiplement this yourself (bad idea) or use a library like the Stanford JS Crypto library (good idea).
As far as the File API goes, it is implemented in the bleeding edge version of every major desktop browser, as well as the latest Android browser shipping. iOS is not supported as it doesn't really have a filesystem. Check out caniuse.com for the latest stats.
Simple answer, you can't. That is if you want to support all browsers at least. I think both Chrome and FireFox supports the reading of files on the client, and IE supports it with the help of ActiveX controls, but to get a solution that works in all browsers you have to use a plugin like Flash or Silverlight. Also, when doing file-uploads of video-magnitude (large+ files), I think going for flash or the likes from the start is a good idea anyhow, but that's just my opinion.

Is it possible to remember the filename from a fileupload field and then later launch that file via javascript?

I have a HTML file upload field from which I'm reading the file name of the file that the user specifies. The actual contents of the file is never uploaded.
At a later stage, is it possible to construct a link using this file name information so that if the user clicks on this link, the original file is launched into a new browser window? If not, what are the reason for disallowing this behaviour?
The purpose of such a feature is to store links to documents that are available on a mapped local drive or a network share.
Most likely, no.
T.J.'s Crowder answer is correct but do note that on virtually all modern browsers that will work only if the webpage you are viewing (with the input type=file) is itself a file:///.
From your question it appears to be some kind of internal company website, which most likely will have its own web server.
You'll notice that in newer web browsers your client-side code will not actually be able to read the complete pathname of a file chosen by a user. That's a security measure. IE8 provides you with some sort of obviously fake directory name, while Firefox and the Webkit browsers just strip off everything other than the file name.
Thus, I don't think you'll be able to do what you want, at all.
edit: info from msdn: http://msdn.microsoft.com/en-us/library/ms535128%28VS.85%29.aspx
New answer
Since Andreas pointed out (quite kindly!) that my old answer (below), while correct, was almost certainly useless, I thought I'd take another swing at it with something I only learned about a few days ago: The new File API from the W3C.
You won't be able to make much use of this now (except on Firefox 3.6 or above), but before too long it'll find its way into modern browsers. It actually gives you access to local files, as long as the user has explicitly selected the file for you (via an input type="file" element). You still can't see their paths, but you can open and read them from the browser (yes, really). So you could open a new window, open the file, and write the contents to the new window. Whether that will really do what you want is another question (you'll have fun writing binary files to a new window, for instance, even though the File API lets you read them just fine), but hey, it's there.
Old answer
(Although you can do the below, Andreas points out that it won't work on just about any browser unless the page the link is in is also served via a file:// URL. So, not much use then.)
You should be able to use a file:// URL for that, e.g., c:\test.txt becomes file:///C:/test.txt. Then the link just uses the URL and the target="_new" attribute telling the browser to open a new window/tab, e.g.:
<a href='file:///C:/test.txt' target='_new'>link to test.txt</a>

Is it possible to upload a whole folder instead of multiple files using Javascript?

Is it possible to upload a whole folder instead of multiple files using Javascript? If so, what is the approach. If there is no straighforward approach, is there any workaround to achieve the same? I have always been curious about this topic. Any insights will help.
No you can't, except if its zipped, or you can use flash, silverlight or applet for uploading more than one file in the same time.
Check these questions:
multiple file upload in just single browse click without jquery
Multiple File Selection For Uploading in ASP.NET
Edit:
For sure uploading multiple files at the same time is available now using html5 https://stackoverflow.com/search?q=multiple+file+upload+html5
EDIT
Turns out this is supported in Chrome 11, and seems to also work on Firefox if you use a vendor prefix:
https://stackoverflow.com/a/5849341/486547
This is definitely possible with a Java applet, however the % of folks with a JRE installed has gotten pretty low these days (< 70%)
Google Drive does this (choose upload, then "Folder..") It works for me (Mac OS X 10.7.5 in Chrome).
I'm not entirely sure how yet. I'm working on a project where this matters, so I've been looking for a while. I'll update as soon as I have more.
Sounds like you're already aware of this, but in the mean time, you can use valums or blueimp to do multiple file upload.
There is no way to do this in most browsers in javascript. Obviously though some (naive) browsers may have this functionality, as the javascript API is defined by the browser itself.
It may be possible using other technologies (such as silverlight, flash, etc) as mentioned in the other answers.
Of course there is. It opens a large security hole, but you can always use WScript and Filesystem ActiveX objects to access OS file system and transfer as many files as you like

Categories

Resources