I am using an input of type=file and I am trying to figure out how to extract the file location from it. I am using this code:
file = $("#uploadFiles").attr("files")[0];
var fileName = file.fileName;
var formData = 'uploadFile=' + fileName;
and when i alert formData, it says "uploadFile=temp.jpg"
What I want is the alerted message to be something like:
"uploadFile=C:\user\doug\documents\pictures\temp.jpg"
But I don't know the attribute of the file object to put in for file.fileName
Generally, you can only rely on the filename being accessible - used mainly as a preliminary extension checking (e.g. (jpe?g|png|gif)$) on the client side (which only serves to benefit the user, to stop them from uploading a 5mb file that will be not validate on the server anyway).
You can access whatever the browser will give you with...
jQuery
$('file[type=input]').val();
JavaScript
document.getElementById('file-input').value;
For security reasons, this is completely impossible in modern browsers.
Related
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.
For one of our customer, we are required to use HTML File Input control, to upload the file to another server using REST Web Services. I was able to achieve this using HTML FileReader.readAsArrayBuffer Method. But since users are using IE8 and IE9, HTML5 APIs are not supported. I tried using below code, but this reads only TXT file not other file types like DOCX or PNG
reader = new ActiveXObject("Scripting.FileSystemObject");
var file = reader.OpenTextFile(filePath, 1); //ActiveX File Object
output = file.ReadAll(); //text contents of file
file.Close(); //close file "input stream"
I use file inputs in a weird working way in IE8, maybe it can help you:
var form = document.createElement("form");
form.method = 'POST';
form.action = url;
form.target = '_blank';
form.encoding = form.enctype = "multipart/form-data";
form.appendChild(fileInput);
document.body.appendChild(form);
form.submit();
It sends the file chosen via fileInput as a POST request to the server, without reading its binary content. Do you absolutely need to read the file client-side ?
If you need cross-site upload, I think there are some iframe hacks for IE working.
Thank You for your quick response. The Web service which I am using is RESTfull service and accept the file as Base64string. So I need to read the file content at client side itself, convert it as Base64 String and pass it to the WebService. So I cannot use Post in there.
This is fully-being a client-side dependent script and at same time there is no handle at server side component I tried options of using ActiveX, but due to some security reason, we cannot proceed with that. I also tried ADO.Stream but even that uses ActiveX.
Thanks,
Aravind
I'm trying to do a simple task. Upload a file with valums file uploader (or fine-uploader) with MVC3 application, save it in database, and let user download it again (with an action returning FileContentResult), but to do that, I need the contentType of file uploaded.
IE9 uses the "UploadHandlerForm" methods in vlaums file uploader (I'm using version 2.1.2), where I can't get the contentType.
When I'm using IE10 for example, the plugin uploads using UploadHandlerXhr, so I can get the content type and post it to the server, with that:
_upload: function(id, params)
{
...
var file = this._files[id];
var type = (file.fileSize != null ? file.fileSize : file.size);
....
//and then, add it to be posted to server:
xhr.setRequestHeader("X-File-Type", type);
}
Is there any way I cant get the contentType of the file from an input file with javascript in older browsers (like IE9)?
It's not clear what you are trying to do here at all. Are you trying to send the content-type of the file in a separate request? If so, why? The content-type is part of each MPE request. Just examine the Content-Type header of the multipart boundary that contains the file data.
Also, don't access variables/functions that start with an underscore. Those are not part of the API and may change or be removed at any time. In the future, I hope to prevent access to these internal entirely.
Same question as here but I need to go to local URL's in Firefox
I tried with code like
var url = "file:///E:/Test/Test.htm";
window.location.href = url;
but id didn't work. Tried to go with window.location = url; and also tried with url = "file://E:/Test/Test.htm"; (double "/" instead of triple "/") and still doesn't work.
Thanks
When I try this:
window.location.href = "file:///C:/Users/Cerbrus/Documents/SomeFile.js"
(Yes, it is a valid path.)
Chrome throws me this error:
Not allowed to load local resource: file:///C:/Users//Documents/File.js
This is because JavaScript does not have access to local files (due to it being sandboxed), and you're setting the new url with JavaScript.
"SandBoxed" means a technology has restricted (or no) access outside a certain set of bounds. In the case of browsers, this means that the code that runs on the page can not access files on your system (Otherwise, it would be easy to "steal" data, by just having a look at the user's file system).
However,
Say, I have 2 files:
C:/Test/Test.htm
C:/Test/Test1.htm
Test.htm contains only this:
<script>
window.location = "file:///C:/Test/Test1.htm";
</script>
This will actually redirect to Test1.htm, since the target file is on the same domain as where the source file's from.
I guess its not allowed to load local resource from javascript
Unless you have a local http server running:
var url = "http://localhost/MySite/Default.aspx";
window.location.href = url;
It will work
You cannot access the file from the local system. Since the Browser works in the sandbox mode and you cannot breach the sandbox and reach the local file system since it would violate the security. Either try to directly load using an AJAX request else what you are trying to do is not possible due to sandbox restrictions and also does not comply with the security policies.
window.location.href = window.location.pathname + (your local file name or path)
window.open(url); // here url can be anything
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.