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/
Related
I am trying to build a webpage that will use an HTML form to upload an image file. Once uploaded, my goal is to convert this image to a favicon, and make it the favicon of the current page. Is there a way to use vanilla JavaScript to achieve this?
If converting to an image to a favicon is not possible with JavaScript on its own, would it be possible to upload a ".ico" file instead, and make it the favicon of the current page?
Vanilla JavaScript is a term used to mean "JavaScript + APIs provided by web browsers", so it can't do the upload part.
You can read the file with a FileReader, and then assign the resulting data: scheme URL as the favicon.
Note that this demo will run, but you won't see the result because the favicon is set on a document loaded inside a frame and not on the SO page it runs in.
document.querySelector('input').addEventListener('change', e => {
const { files } = e.target;
const reader = new FileReader();
reader.addEventListener('load', e => {
const url = reader.result;
console.log(url); // For the sake of this demo
document.querySelector('link[rel=icon]').href = url;
});
// This would benefit from error handling in case a file wasn't selected or it wasn't an image
reader.readAsDataURL(files[0]);
});
<link rel="icon">
<input type=file>
Obviously, this won't persist unless you do something to make it persist (like storing it in local storage and then checking to see if an image is stored there when the page is loaded again.
If you want to upload it then you'll need to send the data to the server. The easiest way to do that is to just have a regular form submission, but you could also use Ajax.
Then you'll need code to store it on the server and add it to the webpage next time someone requests it. The specifics of that really depend on you existing server-side environment.
I face the following problem:
When a user uploads a file with the HTML file input and I then want to receive the file path itself. I only get C:/fakepath/filename.txt for example.
I understand that it is a security reason for browsers to know the exact path of the file. So i was wondering if it is even possible with some hack, some way in .net or with additional jquery/js plugin to get the full path of the file.
Why?
We dont want to upload the file itself to our server filesystem, neither to the database. We just want to store the local path in the database so when the same user opens the site, he can click on that path and his local file system opens.
Any suggestions or recommendations for this approach?
If this is really not possible like
How to resolve the C:\fakepath?
How To Get Real Path Of A File Using Jquery
we would need to come up with a diffrent idea I guess. But since some of the answers are really old, I thought maybe there is a solution to it by now. Thx everyone
As my goal was to make the uploaded file name visible to the End User and then send it via php mail() function, All I did to resolve this was:
in your js file
Old function:
var fileuploadinit = function(){
$('#career_resume').change(function(){
var pathwithfilename = $('#career_resume').val();
$('.uploadedfile').html("Uploaded File Name :" + pathwithfilename).css({
'display':'block'
});
});
};
Corrected function:
var fileuploadinit = function(){
$('#career_resume').change(function(){
var pathwithfilename = $('#career_resume').val();
var filename = pathwithfilename.substring(12);
$('.uploadedfile').html("Uploaded File Name :" + filename).css({
'display':'block'
});
});
};
$(document).ready(function () {
fileuploadinit();
});
Old result:
Uploaded File Name :C:\fakepath\Coverpage.pdf
New result:
Uploaded File Name :Coverpage.pdf
Hope it helps :)
You can't do it.
And if you find a way, it's big security vulnerability that the browser manufacturer will fix when discovered.
You'll need your own code running outside browser-box to do this, since browsers are designed NOT to allow this.
I mean something ugly like ActiveX, flash, COM object, custom browser extenstion or other fancy security breach that can open it's own OpenFileDialog and insert that value in your input field.
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
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
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.