I have a page file-upload.jsp with the code snippet below:
<form action="" id="frmupload" name="frmupload" method="post" enctype="multipart/form-data">
<input type="file" id="upload_file" name="upload_file" multiple="" />
<input type="submit" value="Update" />
</form>
I have 2 questions:
The moment I select some files, i.e the onchange event of the input type file, the file(s) should get uploaded.
I have a Java page that receives multipart request parameter and uploads the file to the said location. My problem is the form submission onchange, so that the Java file can proceed with further operations.
I googled and went through lot of articles. Some say it's not possible to upload files directly via Ajax, some say submit the form to an iframe via Ajax/jQuery.
I tried a lot of code from internet, such as this:
$(document).ready(function(){
$('upload_file').change(function(){
var data = new FormData();
data.append('file', $(this[0].files[0]));
$.ajax({
url: 'photo.jsp',
type: 'post',
contentType: attr('enctype', "multipart/form-data"),
data: data,
success: function(data){
alert(data);
}
})
});
});
but could not get the expected results.
I also need a progress bar for the upload operation.
Look at this example using an IFrame, is in PHP but changing the action should do the trick
Ajax Style File Uploading Using Hidden IFrame
Since you're already using jQuery, I would definitely go for the jQuery Form Plugin, which allows you to do form uploads via AJAX, even if the form contains a file input.
There is an example on its website available that shows how to display a progress bar.
Look at this example it is exact as you want
http://www.asp.net/ajaxlibrary/ajaxcontroltoolkitsamplesite/asyncfileupload/asyncfileupload.aspx
Related
As the title said, I'm stuck on a problem with javascript and form submission.
My problem is, I have an html page, with a form (in a modal exactly but it does not matter here I think). When I submit the form what I need to do is
Open a new page which has to load a pdf of hundred pages (about 100 - 300).
Validate the form.
The problem is, during the validation, if the pdf is not loaded, the page where the form is, is stucked or very very slow. And once the pdf is loaded on the other page, the main page is ok. How do you explain this, and how can I do to avoid this problem ? Maybe validate the form first an then load the page ?
I'm not a javascript expert and a precise explanation on what is going on will be perfect. Thanks.
Here is a piece of code without the real links
<form id="myForm" action="someURL" method="POST">
<input type="hidden" value="someValue" name="someName">
<a class="button" id="myButton" href ="URL_OF_THE_PDF" target="_blank" >
the JS code :
$("#mybutton").on('click', function(){
$.ajax({
type: "POST",
url: myURLForm,
data: form.serialize()
});
});
I put some sample code, I tried different things but none of them works.
You can use a real HTML button here, because you do not need the href.
<button id="myButton" type="button">
That could work:
The onClick function for the button opens an empty page in a new window.
Then it sends the ajax-request first.
When that is done, it loads the pdf file in the new window, which was opened short before.
$("#myButton").on('click', function() {
let myWindow = window.open(empty.html, '_blank');
$.ajax({
type: "POST",
url: myURLForm,
data: form.serialize()
}).done(function() {
myWindow.localtion = URL_OF_THE_PDF;
});
});
see: http://api.jquery.com/jquery.ajax/
How big ist you pdf file with 100-300 pages?
I think the browser is very busy loading the pdf file, because 100-300 pages sounds very big.
So it yould be better doing the ajax request first and loading the pdf file after the ajax request has finished.
I'm trying to use the blueimp/jQuery-File-Upload plugin to programmatically send more than one file input field though the same form.
When user select form files, it just append them in a JS variable to further send them with $('#form').fileupload('send') method on form submission. My goal is to use the exactly same synchronous form I was using before in an asynchronous way. So when user click on form submit button, it prevents default action and them let the plugin to do the task, sending all form data and displaying overall upload progress.
I'm mainly following these guides:
https://github.com/blueimp/jQuery-File-Upload/wiki/API
https://github.com/blueimp/jQuery-File-Upload/wiki/Multiple-File-Input-Fields-in-One-Form
Actually it's almost working, but it does not send more than one input file to the server end. In fileuploadadd event I'm pushing data.files[0] (my file inputs are single file only, but each of them use different accept attributes) to a "global" uploadable array and then on form submission I use something like $('#form').fileupload('send', {files: uploadable}).
I guess I'm not doing it the right way, since only one file is being sent along with form data. What is the correct way to programmatically send more than one file input file using a single form?
I'm also not too confident about overall upload progress... If I use fileuploadprogressall event to read the upload progress will it be reporting the progress of all uploaded files?
JS (simplified)
$(function () {
var uploadable = [];
$('#form').fileupload({
autoUpload: false,
singleFileUploads: false,
add: function (event, data) {
uploadable.push(data.files[0]);
return false;
},
// other event callbacks
})
.prop('disabled', !$.support.fileInput)
.parent().addClass($.support.fileInput ? undefined : 'disabled');
$('#form').submit(function (event) {
event.preventDefault();
$('#form').fileupload('send', {files: uploadable});
});
});
HTML
<form id="form" action="upload" method="post" enctype="multipart/form-data">
<!-- other text/hidden inputs that will also be sent -->
<input type="file" name="image" id="image" accept="image/*" />
<input type="file" name="video" id="video" accept="video/*" />
</form>
uploadable.push(data.files[0])
You vividly told the compiler to only push the first file.
Have you tried using foreach and push all files?
Thank you,
I have some server side restriction.
I want to read file to server one by one using javascript, in such a way that second file will post only after the response from previous file is received.
I have a multiple file upload in my webform as below:
<form id="frmSearchByC2V" method="post" enctype="multipart/form-data">
<input class="file" style="width:50px" type="file" name="c2vFile" id="txtSearchC2V" disabled onchange="locateFiles();" />
</form>
In my javascript i have code something like
<script>
function locateFiles()
{
var fileChooserControl = document.getElementById("txtSearchC2V");
var selectedFileLength = fileChooserControl.files!=null?fileChooserControl.files.length:1;
for(var i=0; i < selectedFileLength; i++)
{
document.forms["frmSearchByC2V"].action="locateFiles.html;
//Ajax call to submit the form
AIM.submit(document.getElementById("frmSearchByC2V"), {'onStart' : function(){return true;}, 'onComplete' : function(response){
loadSearchTargetGrid(response);
}});
document.getElementById("frmSearchByC2V").submit();
}
}
function loadSearchTargetGrid(response)
{
alert(response);
}
</script>
My problem is that whenever i post multiple file using window browser button. Everytime a received the same file to server. eg i choose file.txt,file2.txt,file3.txt and submit the form via javascript, i receive file3.txt in every request i made to the server.
Please provide the solution to fix this issue
If you're using YUI, you can use the Uploader utility. Uploader will upload each file in its own POST request and additionally you can set its simLimit attribute to 1 so that it only makes one request at a time. See: http://yuilibrary.com/yui/docs/uploader/.
I'm new at AJAX and am working on an implementation of a form that will upload a name and a file to a php file that processes the data and sends it to a database for insertion using mysqli. I've tested the php file and it does work. My problem is in the AJAX code. I've tried an implementation using XMLHTTP and using jQuery. Both leave the page and open the PHP file in the browser. As a disclamer, I posted this question to another coding site, a fight ensued between two posters, and so I'm trying here to hopefully get a reasoned and calm response with productive suggestions.
I realize that currently "get" is being sent to the PHP file rather than "post", but PHPStorm tells me that "post" is not available in that form. What's my alternative? Am I on the right track or is there another direction I should go? How do I refresh only the form and keep the PHP page from loading?
Here's the relevant snippet of my code,
<!DOCTYPE html>
<html>
<head>
<script src="jquery.min.js"></script>
<script src="jquery.validate.js"></script>
<script>
$(document).ready(function() {
$('#addForm').validate({
submitHandler: function (form) {
$('input[name="usingAJAX"]', this).val('true');
var url = $(form).prop('action');
var dataToSend = $(form).serialize();
var callback = function(dataReceived) {
$(form).hide();
//result message
$('body').append(dataReceived)
};
var typeOfDataToReceive = 'html';
$.get(url, dataToSend, callback, typeOfDataToReceive),
return false;
}
});
});
</script>
</head>
<body>
<form id="addForm" action="addInfo.php" enctype="multipart/form-data">
<input type="hidden" name="usingAJAX" value="false"/>
<label for="aname">Name: </label>
<input type="text" name="aname" id="aname" class=required/>
<label for="aimage">Photo: </label>
<input id="aimage" type="file" name="aimage" class="required">
<input type="submit" value="ADD"/>
</form>
</body>
</html>
Until recently you could not upload files with ajax.
You still cannot upload the file directly with ajax, but you can do it programatically with HTML5 File API.
Still, if you are looking for simple solutions, try traditional IFrame approach.
If you want bleading edge technology, use File API. Here is some tutorial how to read files with javascript.
The steps to upload with ajax:
Read file with javascript FileReader API.
Post the content of the file, encoded to base64 or something, to the server.
Serverside, decode the contents of the file programatically.
When using this approach, the file will not be handled as a file upload by the server. It will be just another request field with text inside. It is up to you to decode it on the server side.
The filereader API allows you to read the file portion by portion and upload fragments of file, so it would be possible to upload huge files in chunks, but you need to handle it yourself.
Try using plugin jQuery form.js http://www.malsup.com/jquery/form/#file-upload You can upload files with ajax and jQuery. It is easy to use, just need to give #form-id in ajaxSubmit function.
<script>
$(document).ready(function() {
$('#addForm').validate({
submitHandler: function (form) {
$('input[name="usingAJAX"]', this).val('true');
var options = {
url : $(form).prop('action'),
dataToSend : $(form).serialize(),
callback : function(dataReceived) {
$(form).hide();
//result message
$('body').append(dataReceived) },
typeOfDataToReceive = 'html';
//your options here
};
$('#yourFormid').ajaxSubmit(options);
return false;
}
});
});
</script>
How would I edit this so it accepts the image when put in form all other options work just the image not uploading to server or database.
Please could someone help I have looked around and can't find anything that I understand,could someone possibly add a bit of code to this?
Thanks in advance.
<script type="text/javascript">
jQuery(document).ready(function($) {
$("#Submit").click(function() {
var url = "../AdsCreate/CreateCar.php"; // the script where you handle the form input.
$.ajax({
type: "POST",
url: url,
data: $("#myForm").serialize(), // serializes the form's elements.
success: function(html){ $("#right").html(html); }
});
return false; // avoid to execute the actual submit of the form.
});
});
</script>
That's because <input type="file" gets skipped when performing the .serialize() on the form.
It's possible to upload files with JavaScript, but far easier to just do it within the form:
<form action="../AdsCrease/CreateCar.php" method="post" enctype="multipart/form-data">
...
<input type="file" name="myfile" ... />
...
<button type="submit">Submit</button>
</form>
jQuery documentation on .serialize clearly states that file upload is not supported (and indeed you need a multipart/form-data POST submission for uploads, it's not just a query string).
Right before the "example" sections you can find:
Data from file select elements is not serialized.