I am trying to create a form where I can upload demographic information such as name, etc. as well as upload jpg image files. I cannot figure out how to catch the file the user chooses from the browse button. Where is the file name stored? How can I access it for the upload? How can I access it to assign it as a variable eg:
var theFileName;
function()
if (filename !=null) { //manipulate the variable };
else { //something else};
I am new to JavaScript and trying to teach myself with web sources and books and cannot seem to find an answer. In addition to an answer to this question, can anyone suggest a good web source for further information on this subject? The ultimate goal is to be able to upload the info and files with PHP into a database so it can be recalled on another page but a different user.
http://jsfiddle.net/EDfsh/
if you look into this fiddle i've made, you have the code you need ;)
It uses jQuery.
Your HTML Input
<input type="file" id="pic" >
JavaSCript:
function fileName(test){
var source=test.value;
alert(source);
}
$(function(){
$('#pic').bind('change',function(){
fileName(this);
});
});
But you cannot see the source of the file. And you don't have the rights to see the whole path. So you just get the file name.
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[]"/>')
});
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.
im using the blueimp jquery file upload plugin . this code
<script>
$('#fileupload').bind('fileuploadsubmit',function(e,data){
var inputs = data.context.find(':input');
if (inputs.filter('[required][value=""]').first().focus().length){
return false;
}
data.formData = inputs.serializeArray();
});
</script>
is supposed to send all files along with the form data to the server. For some reason its not working . Firebug says ReferenceError: $ is not defined when this page is loaded. Should i define this callback in the main js ? ( I am able to add additional form data for the selected files when uploading and save the names onto the database. When using titles for each uploaded file these values are sent saved as typed when uploaded one by one. When uploaded all at once the value is the same as the first input. This callback supposedly uploads thses data one by one.
As shown in your jsfiddle, all the script includes are placed at the bottom of the page. So you either move them before your script tags, or you move your script tags to the bottom of the page. Otherwise jQuery will not be defined when you want to use it.
Fix this :
(e, data>
to
(e, data)
How to call a javascript file (.js) via Excel VBA?
So as i am opposed to the same kind of problem i'll try to submit you guys my case.
I am trying to automate datas extraction from valeo's catalogue using excel vba macro.
I have a list of références attached to valeo's automotive products (huge list, as more than 3000 thousands items). And i would like to import directly informations from the catalogue wich seems to run under javascript.
The datas i need is the list of every vehicules attached to a reference.
Here is the url: http://outcat-cs.tecdoc.net/ows/en/7FA2A0C501BC34CA4BECB04095663CF1.ows_cs2.srv?view=VIndexFramesetJsp
I'd like to access to the "Direct Article Search" tab, in order to copy a reference directly from an excel tab's cell and then simulate a clic on the reference in order to display the "linked vehicules section" and then to copy them in a new excel sheet.
I already succeede in doing this with html pure programmed webpage (oscaro.com) using the following code :
Set maPageHtml = IE.document
Set Helem = maPageHtml.getElementsByTagName("input")
For i = 0 To Helem.Length - 1
If Helem(i).getAttribute("name") = "toFind" Then Helem(i).Value = "819971" '819971 is the valeo reference searched
If Helem(i).getAttribute("name") = "submit" Then Set Monbouton = Helem(i)
Next
Monbouton.Click 'this does the click on my button Monbouton
But this technique can't be used with valeo website since I am not able (or at least I don't know yet how to do it) to select/click a button when the page is made on javascript, since it doesn't have a name, value or id for the button.
Also it seems that the url in the address field is the same before clicking on the "Direct Article Search" button and after having clicked....
Hope i am clear enought in spite of my english...
Greetings
All the previously suggested approaches sound hacky to me.
For a more reliable solution, embed the Javascript in a COM component via Windows Script Components, and call the Javascript-based COM component as you would any other COM component.
I don't think that there is a direct way to run JavaScript code in VBA.
What you could try to do is to embed the JavaScript code in an HTML form which you could open in a (hidden) browser control. Then fill the form controls via the DOM of the browser control and submit the form. The submit triggers the JavaScript function that you want to call.
Sample (not tested):
VBA:
oIE.Document.frmMain.param1.Value = 5
oIE.Document.frmMain.param2.Value = "6"
oIE.Document.frmMain.submit.click ' this line will call the JavaScript function
HTML:
<div id="submit" > Do Action</div>
<script>
function doAction()
{
// do whatever the code should do
}
</script>
You mean through windows scripting host?
You can shell (use the shell command) out to wscript.exe with the name of the .js file.
But this javascript object model won't be like the one you get in the browser.
It would be helpful if you told us what the javascript was supposed to do.