I have an input file with hidden visibility :
<input type="file" id="fileupload" name="upload" style="visibility: hidden;" />
But I want to use it, without showing it. I will trigger the event through a-tag(hyperlink).
There I have:
//that's fine, open file dialog
document.getElementById('fileupload').click();
//can not take the value of file chosen?
var x = document.getElementById('fileupload').value;
console.log(x);
So how can I take the chosen file without displaying the input ? Is this possible?
You only want to display the filename when someone adds a file?
You could add an eventListener to your file to retrieve the filename:
document.getElementById('fileupload').onchange = function(e) {
console.log(e.target.value);
}
But to upload a file you can just add this hidden file field to a form and submit it.
The first question in my mind is why dont you use jQuery, as its easier.
Second, the input will not actually hold the file per se, but a reference to it. The file will be sent via post (or get) and manipulated server side. Maybe I don't understand correctly what you're trying to do.
Related
I'm trying to pass the contents of an input file asynchronously. The input control is located within an UpdatePanel control. I can only use the HTML input file control and I do not want to generate the postback. Ok. Is there a way, even using JavaScript? To understand better: in my project I must be able to publish posts (like facebook) that have an image besides the text. Therefore it must take place asynchronously. When the user loads the image, the preview is generated by saving the cached data.
<img id="imgoutput"/>
<input id="upload1" type="file" name="upload1" accept="image/*" onchange="loadFile(event)" />
var loadFile = function (event) {
var output = document.getElementById('imgoutput');
output.src = URL.createObjectURL(event.target.files[0]);
};
Is there a way to somehow manage to recover the file by acting on the cache when I try to publish the post?
Thank you
I am developing a page (one-time use - its registration page) when a visitor opens dialog box and uploads files throught input type file multiple.
All worked fine, but my client just told me they want to be able to upload multiple files from different directories. By opening that dialog more times.
Now, normally what happens is that when I open file select dialog another time, the previously selected files got removed from the input.
Is there any way (pure HTML or JS) that I could add the possibility to "stack" files - add them to the selection (maybe some JS object later converted back to input type file?) so that files can be added to the list of files in the input?
I would say that you have two options here.
Stick to classic form
If you want to keep the classic form logic, you will have to add more file inputs to keep your old selections.
A short script will look like :
$('input[type="file"]').on('change', function() { $(this).append('<input type="file" name="file[]"/>') });
So to add more files, the user can click on the next file input.
You can then enhance it to make it nicer with design stuff and remove functionality.
The HTML5 way
While the previous idea is simple, I think it lacks of design and user friendliness.
So the other idea is a more advance way, which will need a bit more of work but will let you do what you want and more (You could add drag/drop for instance).
So the basic idea is that when the user select a file, you will get the file in Javascript, you can do it by using the FileReader object.
When you have the file content, you can just queue it on a variable.
var queue = [];
function addFile(event) {
var files = event.target.files, i = 0, j = files.length, file, reader;
reader = new FileReader();
reader.onloadend = function () {
queue.push{ reader.result };
};
for (i = 0; i < j; i += 1) {
file = files[i];
reader.readAsBinaryString(file);
}
}
Note that If you want to keep the select dialog, you will need to keep the file input.
Once your user valid the form, you should send your other inputs first by Ajax (you want to stay on the page, or you'll have to store your files like in the localStorage which I think is a bad idea).
Then you'll have to send your file to the server using Ajax requests as well, it's easy as just sending the file bits to the server. And on your server you will have to get those bits and simply put it on a file (If you have a specific language for the server part we can extend on how doing it).
You can go then further that way and have the possibility to get the progress of the upload, cancel an upload, slice your files if you have size limitation, do drag and drop,...
Of course, you will to considerate that some browsers have some issues with this object, but it tend to be good everywhere.
Note on the "classic form"/JQuery solution given by Gregoire: this will not work on the newly added inputs, as the listener is not active on them. If you modify this to use delegated events you have a working clean solution:
<div id="files">
<input type="file" name="file[]" />
</div>
$("#files").on("change", "input", function(event){
$('#files').append('<input type="file" name="file[]"/>')
});
I need to execute certain piece of code after user chooses file from file input. The tricky part is I cannot check the input for it, so:
$('input').change ->
is out of the question, I need to detect user clicking "Open" button. Is it possible?
You'd need to check the file input's FileList.
<input type="file" id="file">
$('#file').on('change', function() {
return console.log($(this)[0].files);
});
Worth bearing in mind that if you were to select a file and then go back in and choose the same file a second time, the function will not fire as the input hasn't truly changed.
In this scenario you'd need to set a flag somewhere that resets when you click the input (or something similar).
SHORT VERSION:
How do I attach an image object from the Document Object Model, using JavaScript, to a form so it can be sent to the server, without the user having to manually attach it using the input type=file tag?
Description:
I need a user to be able to look at a series of pics on a web page that were pulled in as the preview of a link he pasted, choose one, and have it automatically attach to a form, to be sent with text he wrote and processed by existing PHP as part of a new post, exactly as if he'd used an input type="file" interface to attach it.
The problem is that the pic exists in the browser as part of the Document Object Model, and it needs to somehow become an attachment into his form, to submit with his text as a new post. I've tried making a hidden input and making its value equal to the image, but that seems not to work.
The solution can be in jQuery, or hand-coded, I've been using JavaScript for 18 years, so I can understand either one...I just don't know how to attach a DOM object as a file to post to the server and process as part of a form.
Example Code:
This is not the actual code, which is complex and involves using JSON to pull a preview of a URL in PHP and send it back to the user, but it summarizes the problem:
<img id="image[0]" src="images/image0.jpg" onclick="attachimage(0)"/>
<img id="image[1]" src="images/image1.jpg" onclick="attachimage(1)"/>
<img id="image[2]" src="images/image2.jpg" onclick="attachimage(2)"/>
<form method="post">
<input type="text" name="title"/>
<textarea name="description"></textarea>
<input type="hidden" name="theimage" id="theimage">
<input type="submit" name="post" value="save">
</form>
<script>
var attachimage = function(item) {
// So far, nothing like this next line has worked for me,
// the image never shows up in the saved post
$("#theimage").val(document.getElementById("image[" + item + "]"));
}
</script>
CONTEXT:
I am working on a Wordpress website, using BuddyPress, to allow users to post their own links (a-la Digg and Reddit) without having Editor permission and using the Dashboard. I'm using a plugin called BuddyBlog (which uses bp-simple-front-end-post) to let users do this, which works fine...
But the owner also wants a preview to come up when they paste in a URL, just like it does on Facebook. I found nothing that already integrates the two features (user posts AND preview), so I pulled some open source code from the web that takes the URL, sends it via JSON to the server, which grabs the title, description, and images via PHP and sends the results back as a formatted HTML block. I then grab the values of those results and insert them into the BuddyBlog form fields...but BuddyBlog's form anticipates the image coming to it via:
<input type="file" name="bp_simple_post_upload_0">
...and I don't think I can simply set the value of bp_simple_post_upload_0 to be equal to the source of image[0]
If you've already processed the images on the server and created the previews, it means they're already there. So just pass in some variable representing which picture was selected and get the corresponding image. It's already on the server.
If the images are generated dynamically, with canvases or whatnot, you could send a base64 hash of them.
I am trying to implement a message functionality. In this the user is allowed to upload an image. My upload function is working fine. But i want to the preview of the image that the user wants to upload before he actually clicks the submit button. My working code for image input so far is
<input name="attach" type="file" id="attach" />
I have searched a lot and have reached a conclusion that i will have to use java-script or j-query for this i created a onchange="readURL(this);" function and placed it in input. I also created an image tag in which the image will be displayed <img id="preview_img" style="max-width: 130px; max-height: 130px; display: none" src=""/> From here on i am confused. How will i change the image src with java-script or what value will i change it to?
you can put this in some jQuery event ( 'click' , 'load', not sure when you want this to happen):
$('#preview_img').attr('src', '...');
Set the data URI with the image content to the src attribute. As long as you don't have the image uploaded on the server, you can load its content content in the data URI format by FileReader.readAsDataURL in your readURL, where you have access to the selected file either via event.target.files or via the this which you send there in your code.
Have a look at an answer to a similar problem; it accesses the input element by its ID, but you can easily adapt it to consume the element you send to the readURL.