I am new to HTML5 and javascript and I have a question.
I have the following HTML code
<img id='image_preview'/>";
<input type='file' name='fileUpl' id='fileUpl' onchange='doUpl();' accept='image/*'/>
So in short, there is a button, every time I click it, doUpl() is executed. It loads a picture and shows a preview of the picture into <img ... >
the js function is
function doUpl() {
var file = document.getElementById('fileUpl').files[0];
...
dataUrl = canvas.toDataURL("image/jpeg");
document.getElementById('image_preview').src = dataUrl;
...
I would like to have the input field pre-loaded with a default picture path (ex. c:\test.jpg) and the preview of test.jpg already shown when the page is loaded the first time. If the button is pressed the picture is updated.
At the moment, when I first load the html page there is no preview and the input path is empty.
Can anyone help me with this?
Thanks :)
edit: sorry for the confusion. the test img is of course on the server not on the client PC.
I would like to have the input field pre-loaded with a default picture path (ex. c:\test.jpg)
You can do that using the value attribute. Something like this:
<input type='file' name='fileUpl' id='fileUpl' onchange='doUpl();' accept='image/*' value='c:\test.jpg'/>
the preview of test.jpg already shown when the page is loaded the first time.
There are a couple ways you can do this. The basic one is to do like above, using the src attribute:
<img id='image_preview' src='c:\test.jpg'/>"
But, I think is better to do using javascript, because, if one day you need to change this standard image, you only change it on the input element.
</body>
<script>
// self executing function here
(function() {
doUpl(); //this will execute when page is loaded.
})();
</script>
P.S. This is only possible if you have c:\test.jpg on your server
You can check if there is something on the input and fake the img and fake the path but you cannot get a real image from the user hard drive because it's security
If you are talking about preloading images from the client's filesystem, I'm afraid this is not possible due to obvious security reasons:
The specification of the File API states that:
(..) This specification also assumes that the primary user interaction is
with the element of HTML forms [HTML], and that
all files that are being read by FileReader objects have first been
selected by the user (..)
Related
How to get full path of file while selecting file using <input type=‘file’>
<input type="file" id="fileUpload">
<script type="text/javascript">
function getFilePath(){
$('input[type=file]').change(function () {
var filePath=$('#fileUpload').val();
});
}
</script>
but the filePath var contains only name of selected file, not the full path.
I searched it on net, but it seems that for security reasons browsers (FF,chrome) just give name of file.
Is there any other way to get full path of selected file?
For security reasons browsers do not allow this, i.e. JavaScript in browser has no access to the File System, however using HTML5 File API, only Firefox provides a mozFullPath property, but if you try to get the value it returns an empty string:
$('input[type=file]').change(function () {
console.log(this.files[0].mozFullPath);
});
https://jsfiddle.net/SCK5A/
So don't waste your time.
edit: If you need the file's path for reading a file you can use the FileReader API instead. Here is a related question on SO: Preview an image before it is uploaded.
Try This:
It'll give you a temporary path not the accurate path, you can use this script if you want to show selected images as in this jsfiddle example(Try it by selectng images as well as other files):-
JSFIDDLE
Here is the code :-
HTML:-
<input type="file" id="i_file" value="">
<input type="button" id="i_submit" value="Submit">
<br>
<img src="" width="200" style="display:none;" />
<br>
<div id="disp_tmp_path"></div>
JS:-
$('#i_file').change( function(event) {
var tmppath = URL.createObjectURL(event.target.files[0]);
$("img").fadeIn("fast").attr('src',URL.createObjectURL(event.target.files[0]));
$("#disp_tmp_path").html("Temporary Path(Copy it and try pasting it in browser address bar) --> <strong>["+tmppath+"]</strong>");
});
Its not exactly what you were looking for, but may be it can help you somewhere.
You cannot do so - the browser will not allow this because of security concerns.
When a file is selected by using the input type=file object, the value
of the value property depends on the value of the "Include local
directory path when uploading files to a server" security setting for
the security zone used to display the Web page containing the input
object.
The fully qualified filename of the selected file is returned only
when this setting is enabled. When the setting is disabled, Internet
Explorer 8 replaces the local drive and directory path with the string
C:\fakepath\ in order to prevent inappropriate information disclosure.
And other
You missed ); this at the end of the change event function.
Also do not create function for change event instead just use it as below,
<script type="text/javascript">
$(function()
{
$('#fileUpload').on('change',function ()
{
var filePath = $(this).val();
console.log(filePath);
});
});
</script>
You can't.
Security stops you for knowing anything about the filing system of the client computer - it may not even have one! It could be a MAC, a PC, a Tablet or an internet enabled fridge - you don't know, can't know and won't know. And letting you have the full path could give you some information about the client - particularly if it is a network drive for example.
In fact you can get it under particular conditions, but it requires an ActiveX control, and will not work in 99.99% of circumstances.
You can't use it to restore the file to the original location anyway (as you have absolutely no control over where downloads are stored, or even if they are stored) so in practice it is not a lot of use to you anyway.
Did you mean this?
$('#i_file').change( function(event) {
var tmppath = URL.createObjectURL(event.target.files[0]);
$("img").fadeIn("fast").attr('src',tmppath);
});
You can use the following code to get a working local URL for the uploaded file:
<script type="text/javascript">
var path = (window.URL || window.webkitURL).createObjectURL(file);
console.log('path', path);
</script>
One interesting note: although this isn't available in on the web, if you're using JS in Electron then you can do this.
Using the standard HTML5 file input, you'll receive an extra path property on selected files, containing the real file path.
Full docs here: https://github.com/electron/electron/blob/master/docs/api/file-object.md
You can, if uploading an entire folder is an option for you
<input type="file" webkitdirectory directory multiple/>
change event will contain:
.target.files[...].webkitRelativePath: "FOLDER/FILE.ext"
but it doesn't contain the whole absolute path, only the relative one. Supported in Firefox also.
you should never do so... and I think trying it in latest browsers is useless(from what I know)... all latest browsers on the other hand, will not allow this...
some other links that you can go through, to find a workaround like getting the value serverside, but not in clientside(javascript)
Full path from file input using jQuery
How to get the file path from HTML input form in Firefox 3
One could use the FileReader API for changing the src of an img element.
https://developer.mozilla.org/en-US/docs/Web/API/FileReader/readAsDataURL
This is a working solution for me
const path = (window.URL || window.webkitURL).createObjectURL(file);
It will return a blob URL to locally access the file.
file element has and array call files it contain all necessary stuff you need
var file = document.getElementById("upload");
file.addEventListener("change", function() {
for (var i = 0; i < file.files.length; i++) {
console.log(file.files[i].name);
}
}, false);
You can get the full path of the selected file to upload only by IE11 and MS Edge.
var fullPath = Request.Form.Files["myFile"].FileName;
$('input[type=file]').change(function () {
console.log(this.files[0].path);
});
This is the correct form.
How to get full path of file while selecting file using <input type=‘file’>
<input type="file" id="fileUpload">
<script type="text/javascript">
function getFilePath(){
$('input[type=file]').change(function () {
var filePath=$('#fileUpload').val();
});
}
</script>
but the filePath var contains only name of selected file, not the full path.
I searched it on net, but it seems that for security reasons browsers (FF,chrome) just give name of file.
Is there any other way to get full path of selected file?
For security reasons browsers do not allow this, i.e. JavaScript in browser has no access to the File System, however using HTML5 File API, only Firefox provides a mozFullPath property, but if you try to get the value it returns an empty string:
$('input[type=file]').change(function () {
console.log(this.files[0].mozFullPath);
});
https://jsfiddle.net/SCK5A/
So don't waste your time.
edit: If you need the file's path for reading a file you can use the FileReader API instead. Here is a related question on SO: Preview an image before it is uploaded.
Try This:
It'll give you a temporary path not the accurate path, you can use this script if you want to show selected images as in this jsfiddle example(Try it by selectng images as well as other files):-
JSFIDDLE
Here is the code :-
HTML:-
<input type="file" id="i_file" value="">
<input type="button" id="i_submit" value="Submit">
<br>
<img src="" width="200" style="display:none;" />
<br>
<div id="disp_tmp_path"></div>
JS:-
$('#i_file').change( function(event) {
var tmppath = URL.createObjectURL(event.target.files[0]);
$("img").fadeIn("fast").attr('src',URL.createObjectURL(event.target.files[0]));
$("#disp_tmp_path").html("Temporary Path(Copy it and try pasting it in browser address bar) --> <strong>["+tmppath+"]</strong>");
});
Its not exactly what you were looking for, but may be it can help you somewhere.
You cannot do so - the browser will not allow this because of security concerns.
When a file is selected by using the input type=file object, the value
of the value property depends on the value of the "Include local
directory path when uploading files to a server" security setting for
the security zone used to display the Web page containing the input
object.
The fully qualified filename of the selected file is returned only
when this setting is enabled. When the setting is disabled, Internet
Explorer 8 replaces the local drive and directory path with the string
C:\fakepath\ in order to prevent inappropriate information disclosure.
And other
You missed ); this at the end of the change event function.
Also do not create function for change event instead just use it as below,
<script type="text/javascript">
$(function()
{
$('#fileUpload').on('change',function ()
{
var filePath = $(this).val();
console.log(filePath);
});
});
</script>
You can't.
Security stops you for knowing anything about the filing system of the client computer - it may not even have one! It could be a MAC, a PC, a Tablet or an internet enabled fridge - you don't know, can't know and won't know. And letting you have the full path could give you some information about the client - particularly if it is a network drive for example.
In fact you can get it under particular conditions, but it requires an ActiveX control, and will not work in 99.99% of circumstances.
You can't use it to restore the file to the original location anyway (as you have absolutely no control over where downloads are stored, or even if they are stored) so in practice it is not a lot of use to you anyway.
Did you mean this?
$('#i_file').change( function(event) {
var tmppath = URL.createObjectURL(event.target.files[0]);
$("img").fadeIn("fast").attr('src',tmppath);
});
You can use the following code to get a working local URL for the uploaded file:
<script type="text/javascript">
var path = (window.URL || window.webkitURL).createObjectURL(file);
console.log('path', path);
</script>
One interesting note: although this isn't available in on the web, if you're using JS in Electron then you can do this.
Using the standard HTML5 file input, you'll receive an extra path property on selected files, containing the real file path.
Full docs here: https://github.com/electron/electron/blob/master/docs/api/file-object.md
You can, if uploading an entire folder is an option for you
<input type="file" webkitdirectory directory multiple/>
change event will contain:
.target.files[...].webkitRelativePath: "FOLDER/FILE.ext"
but it doesn't contain the whole absolute path, only the relative one. Supported in Firefox also.
you should never do so... and I think trying it in latest browsers is useless(from what I know)... all latest browsers on the other hand, will not allow this...
some other links that you can go through, to find a workaround like getting the value serverside, but not in clientside(javascript)
Full path from file input using jQuery
How to get the file path from HTML input form in Firefox 3
One could use the FileReader API for changing the src of an img element.
https://developer.mozilla.org/en-US/docs/Web/API/FileReader/readAsDataURL
This is a working solution for me
const path = (window.URL || window.webkitURL).createObjectURL(file);
It will return a blob URL to locally access the file.
file element has and array call files it contain all necessary stuff you need
var file = document.getElementById("upload");
file.addEventListener("change", function() {
for (var i = 0; i < file.files.length; i++) {
console.log(file.files[i].name);
}
}, false);
You can get the full path of the selected file to upload only by IE11 and MS Edge.
var fullPath = Request.Form.Files["myFile"].FileName;
$('input[type=file]').change(function () {
console.log(this.files[0].path);
});
This is the correct form.
I've this in my html file
<div class="change">
<div id="changed" onclick="change_DImage()">New Upload...</div>
<input id="browse" type="file" onchange="ImagLoc()">
</div>
and this in javascript file
function change_DImage(){
document.getElementById("browse").click();
}
function ImagLoc(){
var x = (document.getElementById("browse").value).toString();
var ImgId = x.substr(12,6);
var NewImg = "url('./image/MyAlbum/" + ImgId + "')";
document.getElementById("dailyPic").style.backgroundImage = NewImg;
}
it's work pretty well but when I refresh my browser it'll change back to the default
for this in css file
background-image: url("../image/smokebird.jpg");
On page reload obviously image is going to reset to the original image. To keep it as it is even after page refresh you can do,
Save the image in Cookie (base 64 format), but there is a size limit since you can save small size images only.
On image select, you can save the image file remotely on your server asynchronously (using AJAX) and you can recall the image using the server session.
Javascript manipulates the only current state of the Html, not the file on server side. To handle it, you have to store state on server side, and change it both client and server side on button click.
Storing changed value on browser's cookie or local storage, and get stored one on page load is another option.
localStorage example:jsfiddle
However localStorage can be easily cleaned by user, even by mistake. I have found this answer useful about how it can be cleaned: SO link. Other drawback (if your really care about it) is a need of use Inline styling. There is attr css function but other than content usage is currently limited so I would stick to Inline styling.
I made more understandable version including your code, here:
jsfiddle, however I am not sure what this line and function suppose to do so I have removed it:
<div id="changed" onclick="change_DImage()">New Upload...</div>
Edit:
obviously second jsfiddle code will not work on jsfiddle, you need to inject it to your code.
This is for a Javascript application that is only intended to run on a local machine, accessing many large image files from local disk.
Original code like this:
<script>
// Constants, var inits, etc.
</script>
<-- Then html stuff including some control buttons, each one like this -->
<img id="pgb_runStop" onclick="click_runStop()" src="buttons/but_run.png">
<--then a chunk of javascript related to the buttons -->
The thing works OK, see http://everist.org/NobLog/20150424_js_animated_gallery.htm
Now I want to extend it, so all image pathnames are defined as js constants and vars.
Some will remain fixed during lifetime of the browser page, others will change by
user actions.
I'm stuck with one part of this.
How to get the html parser to pay attention to script blocks WITHIN <img .... > statements?
Specifically, I want to do a document.write() within the image src string.
Like: <img src="<script>document.write(B_PATH)</script>something.png">
This is for the initial page display. The images later get changed by scripts, and that's working OK.
But the html parser doesn't seem to notice scripts inside html elements.
I'm a javascript nubie, so I may have some stupid misconception of how it all works.
Am I just doing it wrong, or is this fundamentally impossible due to reasons?
Here's an example:
<script>
// Constants
PGL_BUT_PATH = "buttons/" // where the button images etc are.
</script>
<-- some html stuff -->
<-- including some control buttons, each one like this -->
<img id="pgb_runStop" onclick="click_runStop()"
src="<script>document.write(PGL_BUT_PATH);</script>but_run.png">
<--then a chunk of javascript related to the buttons -->
In debugger, the img element appears as:
<img id="pgb_runStop" onclick="click_runStop()"
src="<script>document.write(PGL_BUT_PATH);</script>but_run.png"/>
The intent was to get this:
<img id="pgb_runStop" onclick="click_runStop()"
src="buttons/but_run.png"/>
I could just give up with trying to have the page initially render with the correct buttons, and have js correct them afterwards. I'm just surprised... Isn't it possible to evaluate js constants during initial html parsing to construct the DOM, in this way?
Edit to add:
Sorry, I wasn't clear enough in the question. What I want is a way for js to make the html content/DOM correct (per js config values that get defined very early on) BEFORE the page first renders. To avoid any flicker or resizings after first render.
So another solution would be to delay the first page render till after some scripts have run, so they can make initial DOM adjustments before the user sees anything. Any way to do that?
Hmmm... actually that would solve another problem I have. I'll try searching for that.
The semantic templating tools suggest are interesting (had never heard of it. http://www.martin-brennan.com/semantic-templates-with-mustache-js-and-handlebars-js/ ) but am I correct that all such scripting add-ons will execute after the page first renders?
You cannot embed a tag within another tag's attribute. So you cannot embed a <script> inside the src of an <img>. That's just invalid won't-be-parsed HTML.
What you can do, though, is write the attribute after the fact:
<img id="uniqueId">
<script>
var img = document.getElementById('uniqueId')
img.setAttribute('src', PGL_BUT_PATH)
</script>
The <img> tag without a src attribute in that is invalid HTML technically, although it will probably work in any browser anyway. But if you want to stay totally legit, create the <img> with JavaScript too.
<div id="uniqueId"></div>
<script>
var elem = document.getElementById('uniqueId');
var img = document.createElement('img');
img.setAttribute('src', PGL_BUT_PATH);
elem.appendChild(img);
</script>
Tthough I really have no idea why would you like to do this.
This one works for me
<img id="pgb_runStop" onclick="click_runStop()"
src = "about:blank"
onerror="javascript:this.src = PGL_BUT_PATH + 'but_run.png'; this.onerror = null;>
or Another way
<script>
function createImg(src) {
document.write("<img src='" + src + "'>");
}
</script>
<script>createImg(PGL_BUT_PATH + 'but_run.png')</script>
Another more generic approach
<script>
function templete(temp, src) {
document.write(temp.replace("$STR", src));
}
</script>
<script>templete('<img id="pgb_runStop" onclick="click_runStop()" src="$STR"/>', PGL_BUT_PATH + 'but_run.png')</script>
Javascript isn't a templating engine in and of itself, and it looks like that's what you're trying to achieve here. Look into a javascript template library such as Handlebars and you'll have more luck.
Unfortunately, JavaScript doesn't work that way you are setting the src to <script></script> which all the browser thinks of it is just a weird URL. Try:
document.getElementById('pgb_runStop').src = PGL_BUT_PATH + 'but_run.png';
You can change pgb_runStop to whatever is the id of the element.
You can use a Framework like Angular.js to do things like that. I don't use angular.js myself but you can of some pretty incredible stuff with it.
Here's a list of even more engines that you can use
You can also use:
document.getElementById('pgb_runStop')setAttribute('src', PGL_BUT_PATH + 'but_run.png');
Basically, you can do:
(function(){window.onload=function(){
document.getElementById('pgb_runStop')setAttribute('src', PGL_BUT_PATH + 'but_run.png');
};}());
Which should function the exact same
Why not write the whole image in:
document.write('<img src="' + PGL_BUT_PATH + 'but_run.png"/>');
Fiddle
We want to reduce the number of steps it takes for a user to upload a file on our website; so we're using jQuery to open and postback files using the below markup (simplified):
<a onclick="$('#uplRegistrationImage').click();">
Change profile picture
</a>
<!-- Hidden to keep the UI clean -->
<asp:FileUpload ID="uplRegistrationImage"
runat="server"
ClientIDMode="static"
Style="display:none"
onchange="$('#btnSubmitImage').click();" />
<asp:Button runat="server"
ID="btnSubmitImage"
ClientIDMode="static"
Style="display:none"
OnClick="btnSubmitImage_OnClick"
UseSubmitBehavior="False" />
This works absolutely fine in Firefox and Chrome; opening the file dialog when the link is clicked and firing the postback when a file is selected.
However in IE9 after the file upload has loaded and a user has selected a file; insteaed of the OnChange working I get a "SCRIPT5 Access is denied" error. I've tried setting an arbitrary timeout, setting intervals to check if a file is given to no avail.
There are a number of other questions relating to this; however none appear to have a decent answer (One said set the file dialog to be transparent and hover behind a button!)
Has anyone else resolved this? Or is it absolutely necessary that I provide a button for IE users?
For security reasons, what you are trying to do is not possible. It seems to be the IE9 will not let you submit a form in this way unless it was an actual mouse click on the File Upload control that triggers it.
For arguments sake, I was able to use your code to do the submit in the change handler, but it worked only when I clicked the Browse button myself. I even set up polling in the $(document).ready method for a variable set by the change handler that indicates a submission should be triggered - this didn't work either.
The solutions to this problem appear to be:
Styling the control in such a way that it sits behind a button. You mentioned this in your question, but the answer provided by Romas here In JavaScript can I make a "click" event fire programmatically for a file input element? does in fact work (I tried in IE9, Chrome v23 and FF v15).
Using a Flash-based approach (GMail does this). I tried out the Uploadify demo and it seems to work quite nicely.
Styling a File Upload:
http://www.quirksmode.org/dom/inputfile.html
http://www.shauninman.com/archive/2007/09/10/styling_file_inputs_with_css_and_the_dom
References:
jQuery : simulating a click on a <input type="file" /> doesn't work in Firefox?
IE9 file input triggering using Javascript
getting access is denied error on IE8
Hey this solution works.
for download we should be using MSBLOB
$scope.getSingleInvoicePDF = function(invoiceNumberEntity) {
var fileName = invoiceNumberEntity + ".pdf";
var pdfDownload = document.createElement("a");
document.body.appendChild(pdfDownload);
AngularWebService.getFileWithSuffix("ezbillpdfget",invoiceNumberEntity,"pdf" ).then(function(returnedJSON) {
var fileBlob = new Blob([returnedJSON.data], {type: 'application/pdf'});
if (navigator.appVersion.toString().indexOf('.NET') > 0) { // for IE browser
window.navigator.msSaveBlob(fileBlob, fileName);
} else { // for other browsers
var fileURL = window.URL.createObjectURL(fileBlob);
pdfDownload.href = fileURL;
pdfDownload.download = fileName;
pdfDownload.click();
}
});
};
This solution looks like it might work. You'll have to wrap it in a <form> and get it to post in the jquery change handler, and probably handle it in form_load using the __eventtarget or and iframe or whatever it is that web forms uses, but it allows you to select a file, and by submitting the form, it should send it. I can't test it however, since I don't have an environment set up at home.
http://jsfiddle.net/axpLc/1/
<a onclick="$('#inputFile').click();">
Change profile picture
</a>
<div id='divHide'>
<input id='inputFile' type='file' />
</div>
$('#inputFile').change(function() { alert('ran'); });
#divHide { display:none; }
Well, like SLC stated you should utilize the <Form> tag.
First you should indicate the amount of files; which should be determined by your input fields. The second step will be to stack them into an array.
<input type="file" class="upload" name="fileX[]"/>
Then create a loop; by looping it will automatically be determined based on the input field it's currently on.
$("input[#type=file]:nth(" + n +")")
Then you'll notice that each file chosen; will replace the input name to the file-name. That should be a very, very basic way to submit multiple files through jQuery.
If you'd like a single item:
$("input[#type=file]").change(function(){
doIt(this, fileMax);
});
That should create a Div where the maximum file found; and attaches to the onEvent. The correlating code above would need these also:
var fileMax = 3;
<input type="file" class="upload" name="fileX[]" />
This should navigate the DOM parent tree; then create the fields respectively. That is one way; the other way is the one you see above with SLC. There are quite a few ways to do it; it's just how much of jQuery do you want manipulating it?
Hopefully that helps; sorry if I misunderstood your question.