Ajax file upload: what happens by default in form.onsubmit()? - javascript

I have a Java servlet that receives a file, processes it and then writes the resulting file back through HttpServletResponse's OutputStream.
For upload, I use a simple form:
<form id="upload-form" action="MyServlet" method="POST" enctype="multipart/form-data">
Select file to convert:
<input type="file" id="file-select" name="myfile" />
<button type="submit" id="upload-button">Upload</button>
</form>
After the file has been processed, a download dialog opens automatically.
Since processing may take a while (something like 30 seconds plus upload time), I wanted to provide some progress information through a websocket on the same page. This works if I do this:
var uploadForm = document.getElementById("upload-form");
var fileSelect = document.getElementById("file-select");
var uploadButton = document.getElementById("upload-button");
var httpRequest = new XMLHttpRequest();
uploadForm.onsubmit = function(event) {
event.preventDefault();
event.stopPropagation();
var file = fileSelect.files[0];
var formData = new FormData();
formData.append("myfile", file, file.name);
httpRequest.open("POST", "MyServlet", true);
httpRequest.send(formData);
};
The essential commands here seem to be event.preventDefault and event.stopPropagation.
The thing is: with this code, I get my progress info - but my download window never appears. If I comment out the two commands, it's the other way around. What happens by default when submitting a form, and (how) can I trigger that manually, so that I get both progress info AND the resulting file?
Note: I'm not using jQuery so far.

Related

$_FILES is empty when I load images with javascript

I have a form to edit existing data but for some reason the images I load are not being detected in the var $_FILES.
The var $_FILES only detect data If I upload more images manually (without javascript code).
Here is my code to load images to the form.
// This images are loaded after the query is executed and then
// I take this images and insert in the form.
var images = document.getElementsByClassName("image-product");
var dataTransfer = new DataTransfer();
for (let image of images) {
fetch(image.src).then(res => res.blob()).then(blob => {
var file = new File([blob], image.id, blob);
dataTransfer.items.add(file);
listImagesForm.push(file);
});
}
var iptImg = document.getElementById("ipt-image");
iptImg.files = dataTransfer.files;
But if I go to the console and execute the command: document.getElementById("ipt-image").files I can see the information of all files.
EDIT:
The code that I use to submit form is simple:
<form class='form-validate' action='./database/db_product.php?action=update' method='POST' enctype='multipart/form-data'>;
<input type="file" multiple class="custom-file-input" id="ipt-image" name="ipt-image[]">
<button type="submit" class="btn btn-lg btn-primary">Save</button>
</form>
I remember again that if I upload more images after this they will be added to existing ones and the $_FILES will detect all the images.

Trying to read a local file on page load in HTML

I'm creating a web application that references a local txt (or csv) file which will change every year. I want to be able to load the contents of the file into a <textarea> on page startup.
Right now, I have functional code for loading the contents into a <textarea> by using the <input> element (thanks to a previous StackOverflow question in 2015). The file is selected and an event listener will call a function once the input state gets changed. My challenge is modifying the code so that the file can be hard-coded and loaded on startup and still calling the function using an event (or changing the function to work without an event call).
index.html
<input type="file" id="fileinput" />
<script type="text/javascript" src="dataLoad.js"></script>
<script type="text/javascript">
document.getElementById('fileinput').addEventListener('change', readSingleFile, false);
</script>
<textarea rows=20 id="area"></textarea>
dataLoad.js
function readSingleFile(evt) {
//Retrieve the first (and only!) File from the FileList object
var f = evt.target.files[0];
if (f) {
var r = new FileReader();
r.onload = function(e) {
var display = "";
//a lot of unimportant stuff here
document.getElementById('area').value = display;
}
r.readAsText(f);
} else {
alert("Failed to load file");
}
}
This works fine, but I don't want to manually select the file to load, I want to hard-code the file. The "a lot of unimportant stuff here" parses the data in the file so I left it out for clarity sake.
You cannot due to security reasons.
You don't want the websites you visit to be able to do this, do you?
Try This:
<object width="300" height="300" type="text/plain" data="password.txt" border="0" >
</object
Assuming the <input type="file" /> has autocomplete on (which I believe it does by default), any files that were chosen/dragged onto the element should still be present on page load, so all you would need to do is manually trigger the change event that you added an eventListener for, like so:
<input type="file" id="fileinput" />
<textarea rows=20 id="area"></textarea>
<script>
var fileInput = document.getElementById('fileinput');
var event = new Event('change');
fileInput.addEventListener('change', readSingleFile, false);
fileInput.dispatchEvent(event);
function readSingleFile(evt) {
var f = evt.target.files[0];
if (f) {
alert("Processing file...");
}
}
</script>
This won't work in JSFiddle as it rebuilds the HTML when you refresh the page, however this works offline for me.

Possible to send an image file to PHP with AJAX?

I'm trying to send an image file along with other text information using AJAX, however I can't get the file part to work, as I don't quite understand how to do it.
Here is the Javascript:
//The user selects a file using an input element with the ID "picInput"
var picInput = document.getElementById("picInput");
picValue = picInput.files[0];
//"postString" is the string with all the other text information that is being sent
//All the other info in it is received fine, it is just the picture having problems
postString += "pic=" + picValue;
var xmlhttp = new XMLHttpRequest;
xmlhttp.open("POST","handler.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send(postString);
And here is the PHP:
$pic = $_FILES['pic'];
ftp_put($ftpCon,"pics/".$name,$pic,FTP_BINARY) or die(mysqli_error($con));
With this code, I get 'undefined index' for the "$pic = $_FILES['pic'];" line.
If I change $_FILES to $_POST I get "ftp_put([object File]): failed to open stream: No such file or directory"
Are you trying to ajax a form content? If yes you could try AJAX form Plugin
$("body").on('submit','form#someForm', function(e){
e.preventDefault();
$(this).ajaxSubmit({
target: '#output',
success: afterSuccess
});
});
Then you'll have to put the file and the rest of your contents in
<form id="someForm" method="post" action="handler.php"></form>
and name your file input like
<input type="file" name="pic" />
the afterSuccess function will be called after everything is done
the #output can be used to show progress or things like that

How to post multiple files to server one by one (due to server side restriction) using javascript from html input type file control

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/.

How to add image to multipart via javascript

I am implementing the dropzone.js file upload. However I do not want dropzone to handle the uploads because it seems like they go in bursts instead of all at once. I would like my photos to be uploaded at one time. To do so users will drag and drop photos into the dropzone area. From here they choose some custom options on the images. Then I would like a user to hit a custom button. This button can perform the following.
Add photos to multiImg[] array
invoke form
After a photo is uplaoded into the dropzone I will have access to all the information about the photo. Name, size, location(on uers computer). I am just unsure how to accomplish step 1 which is to take the photos and pass them into a form via javascript.
Is this even a good approach?
<form method="post" action="" enctype="multipart/form-data">
<input type="file" accept='image/*' name="multiImg[]" id="multiImg" />
Or possibly programatically appending
<input type="file" accept='image/*' name="Img" id="Img" />
Tags to the form and then submitting the form when done would be acceptable as well.
Can you dynamically add to the FileList for an input?
This got me closer to a solution.
xhr = new XMLHttpRequest();
formData = new FormData();
formData.append("" + paramNm + (this.uploadMult ? "[]" : ""), file, fileName);
xhr.send(formData);

Categories

Resources