Jquery upload files when open button is pressed - javascript

i have the following code, the issue i have is that i am getting a error of e.originalEvent.dataTransfer is undefined.
my code is as follows
HTML
Select images: <input type="file" id='fileupload' name="userfile[]" multiple>
Javascript is as follows
var hot = $('#fileupload');
hot.change(function (e)
{
e.preventDefault();
var files = e.originalEvent.dataTransfer.files;
//send dropped files to Server
handleFileUpload(files,hot);
});
function handleFileUpload(files,obj)
{
for (var i = 0; i < files.length; i++)
{
var fd = new FormData();
var e = document.getElementById("child_id");
fd.append('userfile[]', files[i]);
var filename=files[i].name;
var status = new createStatusbar(obj,files[i]); //Using this we can set progress.
status.setFileNameSize(files[i].name,files[i].size);
sendFileToServer(fd,status,filename);
}
}

The attribute files belongs to the input field. This you'll get by the target attribute.
If I test the setting above, I have success with this descriptor:
e.originalEvent.target.files
Then, files is an array of File objects, containing name, lastModifiedDate, type etc.

Related

How to upload multiple files via Html form object with just one input field

I have created a Html form with file input field and multiple attribute activated
<input type="file" name="documents" multiple size="11">
This is the function that submits the form object to client side function
<script>
function handleFormSubmit(formObject) {
var div = document.getElementById('output');
var docs = document.getElementById('myFile');
var firstName = document.getElementById('first').value;
var lastName = document.getElementById('last').value;
var hid = document.getElementById("hidden");
for(i=0;i< docs.files.length ; i++){
div.innerHTML = hid+hid.file+"<h3>Please do not refresh or close the page. Your files are uploading...</h3>";
google.script.run.withSuccessHandler(update).uploadFile(formObject);
docs
}
</script>
This is the client side function implemented
function uploadFile(formObject) {
Logger.log("called");
var firstName=formObject.firstName;
var lastName=formObject.lastName;
var file = formObject.documents;
Logger.log(file);
var root = DriveApp.getRootFolder();
var folder,url;
if(root.getFoldersByName("Application Documents - Clients").hasNext()){
folder = root.getFoldersByName("Application Documents - Clients").next();
} else{
folder = root.createFolder("Application Documents - Clients");
}
if(folder.getFoldersByName(firstName+" "+lastName).hasNext()){
url = folder.getFoldersByName(firstName+" "+lastName).next().createFile(file).getUrl();
} else {
url = folder.createFolder(firstName+" "+lastName).createFile(file).getUrl();
}
return url;
}
The output is, I am getting only the first file uploaded thrice if the total file uploads are 3.
Means its just uploading the first file selected at the time of form submission.
I want to get all selected files uploaded to my drive on the same folder.
Thanks in advance

Use formdata append with #HTML.BeginForm without ajax call

What I'm trying to achieve is to append a file to a post request which I got from a drag & drop field with javascript.
The problem is, I don't want to read all input fields and post the data by ajax call, I want to use the default submit method from #HTML.BeginForm.
When I do this, the multipart doesn't really contain the file.
(Attention: It works when I just submit the file or when I read all input fields manually and submit with a separate ajax.)
My code:
Drag&Drop js:
var file;
var isDragged = false;
var formData;
function dropHandler(ev) {
isDragged = true;
ev.preventDefault();
// Use DataTransfer interface to access the file(s)
for (var i = 0; i < ev.dataTransfer.files.length; i++) {
file = ev.dataTransfer.files[i];
formData = new FormData($("#form"));
formData.append("File.PayLoad", file);
formData.append("File.FileMetadataId", $('#File_FileMetadataId').val())
formData.append("File.FileObjectId", $('#File_FileObjectId').val())
}
}
HTML:
#using (Html.BeginForm("Edit", "DocumentTemplates", FormMethod.Post, new { role = "form", enctype = "multipart/form-data", id = "form" }))
{
#Html.AntiForgeryToken()
<div class="row">
<div class="col-xs-4">
#Html.LabelFor(model => model.Language)
</div>
<div class="col-xs-8">
#Html.HiddenFor(model => model.Language) #Html.DisplayFor(model => model.Language)
</div>
</div>
<div class="row">
<div class="col-xs-8">
#Html.TextBoxFor(model => model.File.Payload, new { type = "file", #id = "browseFile", ondrop = "dropHandler(event);", ondragover = "dragOverHandler(event);" })
#Html.ValidationMessageFor(model => model.File.Payload, null, new { #class = "text-danger" }) or Drag & Drop a File.
</div>
</div>
}
Request in Fiddler with empty Filename:
-----------------------------7e27b381715d4
Content-Disposition: form-data; name="File.FileMetadataId"
44
-----------------------------7e27b381715d4
Content-Disposition: form-data; name="File.FileObjectId"
44
-----------------------------7e27b381715d4
Content-Disposition: form-data; name="File.Payload"; filename=""
Content-Type: application/octet-stream
-----------------------------7e27b381715d4--
UPDATE:
I found out, you can overwrite the files from a file input, but only in Chrome. Since I need it to work on IE 11, this doesn't help me, but maybe it helps someone else. You don't need to append all the form fields, but just set the input type file to your dropped file and submit…
You have several problems there. One of the problems is code below. You missed one } in your code.
If you put it like below, the last value just store in file that is incorrect.
for (var i = 0; i < ev.dataTransfer.files.length; i++) {
file = ev.dataTransfer.files[i];
} // missing }
If you put it like below, the last value just store in formData that is incorrect.
function dropHandler(ev) {
isDragged = true;
ev.preventDefault();
// Use DataTransfer interface to access the file(s)
for (var i = 0; i < ev.dataTransfer.files.length; i++) {
file = ev.dataTransfer.files[i];
formData = new FormData($("#form"));
formData.append("File.PayLoad", file);
formData.append("File.FileMetadataId", $('#File_FileMetadataId').val());
formData.append("File.FileObjectId", $('#File_FileObjectId').val());
}
} // missing }
Second problem is ev.dataTransfer.files. As you can see in File drag and drop, it's better to check ev.dataTransfer.items and sometimes it has your files and ev.dataTransfer.files is empty.
Finally, you can do it like this:
function dropHandler(ev) {
isDragged = true;
ev.preventDefault();
formData = new FormData($("#form"));
if (ev.dataTransfer.items) {
// Use DataTransferItemList interface to access the file(s)
for (var i = 0; i < ev.dataTransfer.items.length; i++) {
// If dropped items aren't files, reject them
if (ev.dataTransfer.items[i].kind === 'file') {
var file = ev.dataTransfer.items[i].getAsFile();
formData.append("File.PayLoad" + i, file);
}
}
} else {
// Use DataTransfer interface to access the file(s)
for (var i = 0; i < ev.dataTransfer.files.length; i++) {
file = ev.dataTransfer.files[i];
formData.append("File.PayLoad" + i, file);
}
}
}

Javascript Add multiple file inputs

I have a form and file input. I want to select images from another folder.
echo '<pre>';
var_dump($_FILES);
echo '</pre>';
When I send my form I need to see all selected images but I see only the last selected.
For example, the first time I select 2 files. After selecting 5 files and submitting my form I see only the last selected files, but I need to send all 7 files. Is it possible??
<form action="" method="POST" enctype="multipart/form-data">
<input type="file" id="sell-images" name="images[]" multiple>
<input type="submit" value="submit">
</form>
I have this function for file counter:
$.fn.fileUploader = function (filesToUpload, sectionIdentifier) {
var fileIdCounter = 0;
this.closest("#sell-images").change(function (evt) {
var output = [];
for (var i = 0; i < evt.target.files.length; i++) {
fileIdCounter++;
var file = evt.target.files[i];
var fileId = sectionIdentifier + fileIdCounter;
filesToUpload.push({
id: fileId,
file: file
});
};
for(var z = 0; z < filesToUpload.length; z++)
{
evt.target.files[z] = filesToUpload[z]['file'];
}
console.log(evt.target.files)
});
return this;
};
Here is my onchange function:
$(document).ready(function() {
var filesToUpload = [];
var files1Uploader = $("#sell-images").fileUploader(filesToUpload, "images[]");
$("#sell-images").on('change',function(e) {
e.preventDefault();
Here I see in console all selected files from another folder
console.log($("#sell-images")[0].files);
var formData = new FormData();
for (var i = 0, len = filesToUpload.length; i < len; i++) {
formData.append("files", filesToUpload[i].file);
}
});
});
Here I have all selected files, but when I want to select a new file and send post in my PHP file, the global variable $_FILES shows me only the last selected files.
How can I send my all selected files?
I can do it with another technique every time when selecting a file with JavaScript hide that input and create new but I don't want that.
..., but I need to send all 7 files. Is it possible??
Yes it is possible.
How can I send my all selected files?
Use the array syntax for multiple files. With the current implementation, the last file overwrites all previous entries in the formData object. So update this line:
formData.append("files", filesToUpload[i].file);
To this:
formData.append("files[]", filesToUpload[i].file);
That way all the files in the array filesToUpload will be sent, instead of just the last one.
See this demonstrated in this plunker.

How to bind files to input[type="file"] in javascript

I have div which was dropzone to drop file(s) in the div,
<div id="dropZone"></div>
<input type="file" id=fileUpload"/>
I want to bind drop files to the html file type "fileUpload" control. I have tried like
but not getting. is it possible?
I have written the script for the div
$('#dropZone').bind('dragenter', ignoreDrag);
$('#dropZone').bind('dragover', ignoreDrag);
$('#dropZone').bind('drop', function (e) {
drop(e);
});
Edited and Added script
//Updated
function ignoreDrag(e) {
e.originalEvent.stopPropagation();
e.originalEvent.preventDefault();
}
//Updated End
and in the drop function
function drop(e) {
ignoreDrag(e);
var dt = e.originalEvent.dataTransfer;
var droppedFiles = dt.files;
if (dt.files.length > 0) {
for (var i = 0; i < dt.files.length; i++) {
var fileName = droppedFiles[0].name;
$("#lblMsg").show();
$("#spnFile").text(fileName);
var formData = new FormData();
formData.append("fileUploaded", droppedFiles);
alert(dt.files[0]);
$("#fileUploaded").bind("val", dt.files[0]);
// Binding to file(s) to the <input type="file"/> but not binding.
}
}
}
Is this possible to bind like above??

Javascript Image Preview for page with lots of forms

I have a bunch of forms on a page that allow a user to edit information for each respective form. One of the inputs for the form is an image upload.
The forms are of the form below:
<form class="myForm" ...>
<div class="imagePreview"></div>
<input type="file" name="myImage" onchange="handleFiles(this.files)" />
</form>
And I have javascript to handle the image preview as follows:
function handleFiles(files) {
$(".obj").remove();
for (var i = 0; i < files.length; i++) {
var file = files[i];
var imageType = /image.*/;
if (!file.type.match(imageType)) {
continue;
}
var pic_div = document.getElementById("imagePreview");
var img = document.createElement("img");
img.classList.add("obj");
img.file = file;
pic_div.appendChild(img);
var reader = new FileReader();
reader.onload = (
function(aImg) {
return function(e) {
aImg.src = e.target.result;
};
}
)(img);
reader.readAsDataURL(file);
}
}
I want to replace the line:
var pic_div = document.getElementById("imagePreview");
with the appropriate line. This is where I am getting confused. I don't know how to refer to the div of class "imagePreview" for THIS FORM of class myForm.
Any help is much appreciated.
The problem is that you're getting the div with the Id imagePreview, when the div in the form have the imagePreview CSS class, what you can do is either give the div the required id, more less like this:
<div id="imagePreview"></div>
Or, if you will have multiple divs with the same class get them using jQuery like this:
$(".imagePreview").each(function(index){
//Do Something
});
Or:
var pic_div = $(".imagePreview")[0]

Categories

Resources