Obtain list of files from input - javascript

I have this input <input type="file" id="file" name="file" accept="image/*" multiple> this allow the user select several images and I need to pass all of them to my FormData so I do this:
var formdata = new FormData();
var files = $('#file')[0].files[0];
formdata.append('file',files);
But that only take the first image from de list, How can i take all the images and store all of them in var files?
Thanks in advance
EDIT: The backend I use is django/python and if I use this way in my backend detect only one image from the list like this [<InMemoryUploadedFile: img.png (image/png)>] and using just var files = $('#file')[0].files; show me nothing.

There are many problems:
You can't redeclare the same variable if you want to keep its previous values
You need to change the index so that it's not saving to the same spot
$("#file") - shouldn't be an array, it's an object so i'm surprised it's not throwing an error
Let's say your code is legit. You could do this:
var files=[];
var length = $("#file").length;
for (i = 0; i < length; i++) {
files[i] = $('#file')[i];
}
formdata.append('file',files);

This was my solution
var formdata = new FormData();
var files=[];
var count = document.getElementById('file').files.length;
for (i = 0; i < cont; i++) {
files[i] = document.getElementById('file').files[i];
formdata.append('file',files[i]);
}
Using JQuery for length only brings me 1 element and gives me more problems so
I use puere JavaScript for this part and works fine

Related

Data erase in an array

I'm new in code with Javascript and I have a problem with an array I need to create.
var tabLine = new Array();
var tabCol = new Array();
var tabComplet = new Array();
var fso, f1, ts, s, cl, ln;
var ForReading = 1;
var i = 0;
function ReadFiles() {
fso = new ActiveXObject("Scripting.FileSystemObject");
// Read the contents of the file.
ts = fso.OpenTextFile("PathToAFile\TextFile.txt", ForReading);
s = ts.ReadAll();
tabLine = s.split('\n');
cl = tabLine.length;
ts.Close();
for (i = 0; i <tabLine.length; i++) {
var tabCol = tabLine[i].split("\t");
for (j=0;j<tabCol.length;j++) {
tabComplet[i,j] = tabCol[j];
alert(tabComplet[i,j]);
}
}
alert(tabComplet[10,5]);
alert(tabComplet[3,5]);
}
ReadFiles();
The file I need to read is a text file; It have many line and each line have information separate by tabulation.
This function read the text file and convert it into an array in two dimensions.
I had some alert to check the contain of my array.
The first alert give me the result I want (it display the content of the array witch is different for each element in the array)but the two other give me the same result. I check with another alert and, in the for boucle, these two element are different.
I make more test and all happen like if my array only have the same line copy/paste.
Thanks in advance for all information that can help me.
Here is an example of file I use :
http://www.k-upload.fr/afficher-fichier-2017-05-18-1b0cfa685testimport2.txt.html
Usually there are bigger than this one but for test it's OK.

How to give a custom name to the objects in an array?

I have an upload form and for adding and deleting the files in a filelist I created an array that contains the files to send them in one request.
Creating the array
var filelist = [];
for(var i = 0; i < data.files.length; i++){
filelist.push(data.files[i]);
console.log(filelist);
}
Result in console
[File, File, File]
The files are contained in the array but now I want to give the names in the array the names of the files for deleting purposes.
So instead of [File, File, File], I would like to have for example [image01.jpg, image02.jpg, image03.jpg]
I have already tried
filelist.push(data.files[i].name);
result
["image01.jpg", "image02.jpg", "image03.jpg"]
But the files aren't added to the array? Can anybody help me with this please?
The reason I'm doing this is because I would like to try to remove files from the array on value and not on index.
code for deleting the files from the array
var idx = filelist.indexOf(file.name);
filelist.splice(idx,1);
You can set the name of the file as a key:
var filelist = {};
for(var i = 0; i < data.files.length; i++) {
var file = data.files[i];
filelist[file.name] = file;
}
And then use the delete operator to delete the file based on its name:
var filename = fileToDelete.name;
delete filelist[filename];

Sort input files after selection

Is there any way for me to sort files for POST to server using any client side solution?
More specific, i am using the following tag <input type="file" name="Myfiles[]" multiple> To choose some images.
With the code at the end i display a preview of the images and using jQuery UI sortable i'm able to change the position of the elements.
So, when i post the data to the server how can i insert the files in the order of the sort? that's the point where i'm stuck
for(var i = 0; i< this.files.length; i++)
{
var file = this.files[i];
if(!file.type.match(‘image’))
continue;
var picReader = new FileReader();
picReader.addEventListener('load',function(event){
var picFile = event.target;
$('#sortable').append('<li><img height="100" width="100" src="'+picFile.result+'" /></li>');
});
picReader.readAsDataURL(file);
}
Assuming you are storing the files into an array:
var storedFiles = [];
You can create a hidden field to store the IDs of the images in the order you want (3,1,2,4..) These IDs must be generated after your images are selected.
Then when the upload button is clicked, grab the sorted contents of the hidden input field and run a for loop to reprocess the order of the files.
var data = new FormData();
var items_array = $('.cvf_hidden_field').val();
var items = items_array.split(',');
for (var i in items){
var item_number = items[i];
data.append('files' + i, storedFiles[item_number]);
}
Then append the sorted files into the variable data, then send it using AJAX:
$.ajax({
url: 'upload.php',
type: 'POST',
contentType: false,
data: data,
processData: false,
cache: false,
success: function(response, textStatus, jqXHR) {}
});
The order in which the server receives the files will be the order in which they were placed in the form to be submitted to the server.
That means it's probably easier to re-order them client-side before submitting e.g. by re-ordering the order in which they appear in the form for submission. Heres a rough-and-ready snippet of what you could use:
var newOrder = [];
for(var i = 0; i< this.files.length; i++){
var indiv_file = this.files[a];
// processing to calculate desired array position for submission
idealPos = function_returning_new_array_position(indiv_file);
newOrder[idealPos] = this.files[a];
}
Thus re-order your 'this.files' array to reflect your chosen order. And use the newOrder array in the form when you submit the files. I can't quite make out what you're doing in the above code, but unless your users are expecting their images to be re-ordered, it could turn out a bit disorienting to see the files they are planning to submit jumping around.
You can use plain JavaScript code to sort the files using the file names and store them as an array.
var files = evt.target.files
var RESULT = []
var m = files.length
for (var a = 0; a < m; a++) {
var min = 0
for (var b = 0; b < (m - 1) - a; b++) {
if ((files[b].name).localeCompare(files[b + 1].name) == 1) {
min = b + 1
}
}
RESULT[a] = files[min]
delete files[min]
}
The above code sorts the uploaded files in ascending order based on the file name and stores it in RESULT.

collect data by id using javascript

I have to save temporary data for my webpage using java script.This is the way that i save i one by one since the data is an array.
var product= new Array();
product[1] = document.getElementById("product[1]").value;
product[2] = document.getElementById("product[2]").value;
This method is working. but when i run it by looping, it doesnt work.
for(var i=1; i < no_item; i++){
product[i] = document.getElementById("product[i]").value;
}
*product[] is a varibale that I take from a html dropdown menu
Can anyone please tell me the problem ? thanks ~ =)
Should be written as, as you are going to be getting the id "product[i]" every time with your original code. This will get "product[1]" then "product[2]" and so on:
for(var i=1; i < no_item; i++){
product.push(document.getElementById("product[" + i + "]").value);
}
Also, as a comment, we tend to prefer var product = []; over var product = new Array(); in javascript but both will work.

Javascript ignoring all files as opposed to one

I'm trying to get my javascript to ignore one file type extension that's held in a folder with a bunch of photoshop images. For all of the other file types in the folder I have it so that these file types populate a window and the user can import into their work space.
I have modified my script to ignore the file extension I want ignored, however it no longer populates the window with all of the other file types containted in the folder. But when I take out the file I want ignore from the folder, the window gets populated as it should.
This is what I have at the moment that checks my folder for the file types:
//Prompt for folder location
var Path = Folder.selectDialog("Select Folder Location for Renders")
// Use the path to the application and append the samples folder
var samplesFolder = Folder(Path)
//Get the files
var fileList = samplesFolder.getFiles()
//Creat Array to hold names
var renderTypes = new Array();
//Parse Initial name to get similar render elements
var beautyRender = fileList[0].name
beautyRender = beautyRender.substr(0, beautyRender.length-4)
//Get the render elements with a similar name
for (var i = 0; i < fileList.length; i++)
{
var filename = fileList[i].name;
if (filename.match(/\.(stitchinfo)$/i) == null)
{
if(fileList[i].name.substring(0,beautyRender.length) === beautyRender)
{
renderTypes.push(fileList[i].name);
}
}
}
Can anyone see what I've done wrong and need to modify?
Update
I'm still trying to get this to work and following the help from one of the posters below I have modified my code to the following:
for (var i = 0; i < fileList.length; i++)
{
var filename = fileList[i].name;
if (filename.match(/\.(stitchinfo)$/i) == null)
{
renderTypes.push(fileList[i].name);
}
}
However, with this new code comes a new problem in that it returns every file contained in the folders and displays it.
I'm still stumped as to how I can get this to work as I would like. Please can anyone help me?
You're creating a sparse array, because you skip elements in renderTypes when you ignore a filename in fileList. That may be confusing your rendering code. Change to:
renderTypes.push(fileList[i].name);
What if :
for (var i = 0; i < fileList.length; i++)
{
var filename = fileList[i].name;
if (filename.match(/\.(stitchinfo)$/i) == null)
{
if(fileList[i].name.substring(0,beautyRender.length) === beautyRender)
{
renderTypes.push(fileList[i].name);
}
}
}
Wrong usage of the array
Missing ";"
Unnecessary use of "continue".
Managed to get a fix for this.
What I've ended up doing is creating a new function and passing that into my call for checking the folder locations.
function ignoreMe(f)
{
return f.name.match(/\.(stitchinfo)$/i) == null;
}
And the folder check:
var fileList = samplesFolder.getFiles(ignoreMe);

Categories