Form's uploaded file disappears on canceling new selection of file - javascript

I have a simple form on my webpage.
<form action="upload.php" method="post" enctype="multipart/form-data">
Select image to upload:
<input id="browse" type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>
Now, my problem is when I browse and choose file to upload it shows which file I am going to upload.
But when I click on Choose file and browse again and this time if I change my mind mid way and hit cancel then old selected image also goes away.
On canceling it removes already selected image also.
Why does this happen and what to do if I want my old selected image to be selected after browsing again and canceling?
Thanks in advance!

Thanks to #Carlos , added this javascript
var input = document.getElementById("browse");
var selectedFile;
input.addEventListener('change', updateImageDisplay);
function updateImageDisplay() {
if(input.files.length==0) {
input.files = selectedFile;
}
else {
selectedFile = input.files;
}
}
and now it works fine! you can check here.

Related

In HTML, how can I build a file picker that can change the image displayed without using action listener?

This is what I have in HTML:
<img src="images/defaultProfile.jpg" id="image">
<input type="file" name="pic" accept="image/*" id="imgPath">
<input type="submit" onclick="uploadImg()">
The image with an id of "image" automatically loads a default image from a designated directory by default. Then, the user can I pick an image from the file picker. When the user hits the submit button written on the last line, The uploadImg() written on javaScript file will get the image from input and change the image displayed.
But, my question is how I can enable the user to change the image by just picking a image file from the directory without hitting the "submit" button.
You can add a change listener to the image input:
document.querySelector('#imgPath').onchange = () => {
console.log('Now uploading...');
// uploadImg();
};
<input type="file" name="pic" accept="image/*" id="imgPath">
Take a look at this Why can't I do <img src="C:/localfile.jpg">?. If your plan is to display an image before uploading to the server, that is not going to work. What you can do is write an "onchange" event (https://www.w3schools.com/jsref/event_onchange.asp) to your file selection input line (2nd line in your code), and upload it to a temporary directory and display it. As the user clicks on the upload button, you can make the change permanent. If the user cancels, you will display the default profile page.

JavaScript function called only once instead of every time

I need a javascript code that checks the input file size before uploading everytime the input value changes (i.e. everytime the user selects a file to upload).
So far I came up with this:
var file = document.getElementById("myFile");
file.addEventListener('change', function() {
if (this.files[0].size > 2*1024*1024) {
alert('Max file size is 2 MB');
file.removeAttribute('value');
file.parentNode.replaceChild(file.cloneNode(true),file);
}
}
);
and the HTML is:
<form action="?" method="post">
<input type="file" id="myFile" name="myFile" />
<input type="submit" value="upload" />
</form>
Now, if I leave the Javascript code like that, it doesn't work at all.
But if I change it like this
window.onload = function() {
// Same code above
}
it works, but only for the first file the user selects.
How can I change it to make it work everytime the user selects a file? (if possible without jQuery)
No need to clone the node etc ... just set the value to '';
file.value = '';
see working snippet
document.getElementById("myFile").addEventListener('change', function() {
if (this.files[0].size > 2*1024*1024) {
alert('Max file size is 2 MB');
this.value='';
}
});
<form action="?" method="post">
<input type="file" id="myFile" name="myFile" />
<input type="submit" value="upload" />
</form>
From the documentation for cloneNode:
Cloning a node copies all of its attributes and their values, including intrinsic (in–line) listeners. It does not copy event listeners added using addEventListener()
You are deleting the element with the event handler on it and replacing it with one that doesn't have a change listener
You need to call addEventListener again (and store file.cloneNode(true), in a variable so you can call addEventListener on it and pass it to replaceChild).

How to get file name in text box on selection (Not like c:/fake path/)

What I want is as soon I choose a file in a file input I want to get the file name in text box named file_name without any click or submit button. I could not figure out the code for it.
<input type="text" name="file_name" id="file_name" class="cfGradient inputField">
<input type="file" name="img1" id="img1" onchange="document.getElementById('file_name').value = this.value">
When I am selecting any file from my E drive the output was c:/fake path/selected file but I need the original path of the selected file. Please provide me the code and idea.
you can use like this.
<input type="file" name="file_name" id="file_name" class="cfGradient inputField">
<script type="text/javascript">
function getFilePath(){
$('input[type=file]').change(function () {
var filePath=$('#file_name').val();
});
}
</script>
hope this will help you thanx.

Upload file not working in Chrome extension option page

I am developing a chrome extension with an option page. On that page I put an upload image option but can't get the file to load in javascript. I have tried many solutions (1st solution, 2nd solution ...) but none worked. The strange thing is, that even an "onclick" attribute in the html code doesn't call the corresponding function. Here is an example of the code:
HTML example:
<input type="file" name="uploadImage" id="uploadImage" />
<button type="submit" id="imageUpload-btn" onclick="myFunction();">Upload</button>
javascript example:
jQuery("#imageUpload-btn").click(function(){
var image = new Image();
image.src = jQuery("#uploadImage").val();
alert(image.src);
image.onload = function(){
alert("on load");
}
image.onerror = function(){
alert("error");
}
});
I get the path of the file in the first alert, but then always the error alert. The function "myFunction()" is not called, but if I open the file directly in a browser the "onclick" trigger works and "myFunction()" is called.
What am I doing wrong or what am I missing?
<form name="Upload" action="#" enctype="multipart/form-data" method="post">
<p>Filename: <INPUT type="file" name="submitfile" id = "submitfile" />
<INPUT type="button" value="Send" onClick="checkSize();" />
</form>
here you are using enctype="multipart/form-data" in this type we dont have opertunity to use
im.src = document.getElementById('submitfile').value;
you need to go for apache.commons.fileupload ServletFileUpload.isMultipartContent(request); which is totally java related.

Making function work for any one of the same type of element

I am trying to create a file upload system. This file upload system works great for the mosot part. The problem comes in because there are multiple HTML elements on the page that have class file and multiple HTML elements that are upload-buttons. Right now file uploading works great only for the first HTML element that contains the upload text field and upload button only, all others fail to work (due to Javascript selecting the [0] object every time).
My question is, how can can I adjust the function below to cater to whatever upload container / button that was used?
Essentially what needs to happen is, if the user clicks on the nth upload button the functions array slots needs to be equal to n-1 somehow.
I appreciate any assistance with this problem.
Many thanks in advance!
$(document).on('click','.upload-button', function(){
var data = new FormData();
jQuery.each($('.file')[0].files, function(i, file) {
data.append('file-'+i, file);
});
//Some more code...
});
HTML
<div class="input-text-field">
<input name="userfile" class="file" type="file" />
<input class="submit upload-button" type="submit" value="Upload" />
</div>
Use prev() to target just the previous .file element, and be aware that your code does'nt have a .file element, it has a #file element, and multiple ID's are invalid.
$(document).on('click','.upload-button', function(){
var data = new FormData();
jQuery.each($(this).prev('.file')[0].files, function(i, file) {
data.append('file-'+i, file);
});
//Some more code...
});
html
<div class="input-text-field">
<input name="userfile" class="file" type="file" />
<input class="submit upload-button" type="submit" value="Upload" />
</div>

Categories

Resources