JQuery: how can I push a file to another input array value? - javascript

I have 2 inputs:
each time, I select some files form temp and I want push to another input files.
I do this step:
chage first iput:
<input type="file" id="temp" name="temp[]" onchange="readFile(this);" multiple />
function readFile(input) {
counter = input.files.length;
for(x = 0; x<counter; x++){
if (input.files && input.files[x]) {
const reader = new FileReader();
reader.onload = function (e) {
// add thumbnail picture
}
reader.readAsDataURL(input.files[x]);
}
}
}
I add this code to main js fuction:
var new_file = [];
new_file["id"] = "1";
new_file["main"] = "0";
new_file["delete"] = "0";
new_file["file"] = input.files[x];
files = $("input[name='files[]']").val();
if(!Array.isArray(files)) files = [];
files.push(new_file);
$("input[name='files[]']").val(input[x]);
So finall code:
function readFile(input) {
counter = input.files.length;
for(x = 0; x<counter; x++){
if (input.files && input.files[x]) {
const reader = new FileReader();
var new_file = [];
new_file["id"] = "1";
new_file["main"] = "0";
new_file["delete"] = "0";
new_file["file"] = input.files[x];
files = $("input[name='files[]']").val();
if(!Array.isArray(files)) files = [];
files.push(new_file);
$("input[name='files[]']").val(input[x]);
reader.onload = function (e) {
// add thumbnail picture
}
reader.readAsDataURL(input.files[x]);
}
}
}
So I have 2 problem:
in server side, I got this:
"files" => array:1 [▼
0 => null
]
but temp is ok:
"temp" => array:1 [▼
0 => UploadedFile {#1349 ▶}
]
Also, in line new_file["file"] = input.files[x];, input.files[x] is not a file. it is an object. how can insert file to new_file["file"]?

You can't move the value of one file input to another, it is a security risk.
From copying the value of a form's file input field to another form's input field
If the end result you want to achieve is to have identical values for both the file inputs when user select files for input[name="temp[]"], consider using clone and replace instead:
$('input[name="temp[]"]').change(function() {
var $clone = $this.clone()
$clone.attr('name', 'files[]');
$('input[name="files[]"]').replaceWith($clone);
});

Related

Append sources of multiple photos selected with <input type="file"> to list so they can be displayed with imglist[i] before uploading

I'm working on a React application and would like to setState to photo sources before uploading. I'm trying to do it with this function here:
const getImagesHandler = () => {
let fileinput = document.getElementById("file-input");
let files = fileinput.files;
let photos = [];
let i = 0;
for(i=0; i<files.length;i++){
photos.push(files[i].SOURCE??);
}
this.setState({Photos: photos)
}
const getImagesHandler = () => {
let photos = [];
var fi = document.getElementById('file-input'); // GET THE FILE INPUT.
// VALIDATE OR CHECK IF ANY FILE IS SELECTED.
if (fi.files.length > 0) {
// RUN A LOOP TO CHECK EACH SELECTED FILE.
for (var i = 0; i <= fi.files.length - 1; i++) {
console.log(fi.files.item(i));
photos.push(fi.files.item(i));
}
}
this.setState({ Photos: photos})

Uploading list of images from a folder AngularJs

I want to upload list of images from a folder and stored them as bytestream in database. I want to give angularjs the folder containing the images instead of selecting multiple files . The part of the code responsible is given below.
$scope.uploadMultipleQuestions = function(e) {
var questionList = []
var difficultyLevel = vm.question.difficultyLevel;
var theFiles = e.files;
for (var i = 0; i < theFiles.length; i++) {
var ques = {};
ques.questionString = theFiles[i].name;
DataUtils.toBase64(theFiles[i], function(base64Data) {
$scope.$apply(function() {
ques.questionImage = base64Data;
});
[![enter image description here][1]][1]
});
ques.questionImageContentType = theFiles[i].type;
ques.questionString = theFiles[i].webkitRelativePath.split("/")[1];
questionList.push(ques);
Question.uploadMultipleQuestions(questionList);
}
for (var i = 0; i < questionList.length; i++) {
console.log(questionList[i]);
}
//Question.uploadMultipleQuestions(questionList);
}
But the problem is I am getting the following details in my log.(Screenshot attached below)
As you can see only the last object contains image data whereas none of the others have any image content.
Let me know why this problem is coming and how to solve the same.
It take a while to convert image to base64, so you have to upload your image after ques.questionImage is filled.
var uploadMultipleQuestions = function(files, i, output) {
if (files.length == i) {
for(var j=0;j<output.length;j++)
console.log(output[j]);
return Question.uploadMultipleQuestions(output);
}
DataUtils.toBase64(files[i], function(base64Data) {
output.push({
questionString: files[i].name,
questionImageContentType: files[i].type,
questionString: files[i].webkitRelativePath.split("/")[1],
questionImage: base64Data
});
uploadMultipleQuestions(files, i+1, output);
});
}
$scope.uploadMultipleQuestions =function(e){
var theFiles = e.files;
uploadMultipleQuestions(theFiles, 0, []);
}

How to work with FileList (from <input type="file">) in Javascript?

In this W3schools example, console.log on the input element reveals a FileInput object:
FileList {0: File, 1: File, length: 2}
How can I work with this? The example demonstrates accessing the file, but every time a user selects new files, the old files disappear. How can I create a new empty FileList and copy it over, so that a user can add more files to the FileList?
I tried this, but it results in two FileList objects, rather than one FileList with all the files:
var fileStore = x.files;
function myFunction(){
var txt = "";
if ('files' in x) {
if (x.files.length == 0) {
txt = "Select one or more files.";
} else {
fileStore += x.files;
console.log(x.files);
console.log(fileStore);
Untested, but this should work
var fileStore = [];
function myFunction(){
var txt = "";
if ('files' in x) {
if (x.files.length == 0) {
txt = "Select one or more files.";
} else {
fileStore.push.apply(fileStore,x.files);
console.log(x.files);
console.log(fileStore);
More on Function::apply
More on Array::push
It is not possible to add File objects to FileList. You can use FormData to append Files to a single object.
var data = new FormData();
document.querySelector("input[type=file]")
.addEventListener("change", function(event) {
for (var i = 0, files = event.target.files; i < files.length; i++) {
data.append("file-" + [...data.keys()].length, files[i], files[i].name)
}
})
An array is fine for holding onto the File instances, but FormData is better if you want to upload them somewhere. If you want to log out or view the FormData, turning it into a Map is an option. Keep in mind that FormData is iterable.
var formData = new FormData();
var index = 0;
function onDrop(event)
{
var dt = event.dataTransfer;
var files = dt.files;
var count = files.length;
output("File Count: " + count + "\n");
for (var i = 0; i < files.length; i++) {
formData.append(files[i].name, files[i]);
}
}
function output(text)
{
document.getElementById("output").textContent += text;
console.dir(new Map(formData));
}
See this JSBin.
it is possible to add files using the datatransfer class
export const makeFileList = files => {
const reducer = (dataTransfer, file) => {
dataTransfer.items.add(file);
return dataTransfer;
}
return files.reduce(reducer, new DataTransfer()).files;
}

event listener 'change' is not engaging?

I'm trying to read in a file, split the words out into an array, count the length of each word, then reassign each word into a new array if the word is greater than a number entered. When the file is selected, thats when the function should execute, perform the above logic and display the result to an element. The EventListener doesn't seem to be getting triggered when I set a breakpoint in Chrome. Any suggestions?
I've included the JS and html for troubleshooting. Thanks in advance!
function filteredWords() {
var fileInput = document.getElementById('fileInput'); //create a variable for the html input
var displayResult = document.getElementById('displayResult'); //create a variable for the html display
var temp = document.getElementById('num').value;
var num = parseInt(temp, 10);
fileInput.addEventListener('change', function (e) {
var file = fileInput.files[0]; //store the first file into a variable
var textType = /text.*/; //create a variable for checking if file type is text
if (file.type.match(textType)) { //if the file is of type text
var reader = new FileReader(); //create a new file reader object
var text = "";
var wordArray = [];
var filteredArray = [];
reader.readAsText(file); // read the file
reader.onload = function (e) { //for the onload event
text = reader.result; //assign result to new variable
wordArray = text.split(' '); //split the text words into an array
for (i = 0; i < wordArray.length; i++) { //loop through the array and replace largest word with largest in array
if (wordArray[i].length > num) {
filteredArray += wordArray[i];
}
}
displayResult.innerHTML = "Your filtered words are: "; //display the result in the browser element
for (i = 0; i < filteredArray.length; i++) {
displayResult.innerHTML = largestWord + ", ";
}
};
} else { //display a message if file wasn't read
displayResult.innerHTML = "File not supported!";
}
});
}
//inputs
<input class="" type="number" id="num" />
<input type="file" onclick="filteredWords()" id="fileInput" />
//display
<p id="displayResult" class="control-label"></p>

Javascript DOM Mouse Event is not working for IE and Mozilla

Working on the Custom File upload application. I have 2 major issues:
The following given below code is not Opening the File Dialogue Box for Mozilla and IE.
In Chrome its working, but when I select File on First Click, it never adds file to the body. But in second click it adds the file which was Browse in First Click to the body.
Any help for the above issues will be appreciated.
function perform1Click(node) {
alert("INIT");
var evt = document.createEvent("MouseEvents");
evt.initEvent("click", true, false);
node.dispatchEvent(evt);
alert(3)
getFile(evt);
}
function getFile(event) {
var files = event.target.files;
var totalSize = 0;
if (totalSize > 1024*10) {
alert('Total size exceed 1 Mb.');
return;
}
//alert(files)
//alert(files.length);
for (var i = 0, f; f = files[i]; i++) {
displayFileList(f.name, f.size);
totalSize = totalSize+f.size;
}
}
function displayFileList(name, size) {
if (name != '') {
var top_plugin = document.getElementById('top_plugin');
// create tag
var ptag = document.createElement("p");
// create div
var divBox = document.createElement("div");
divBox.setAttribute('class', 'divBox');
// create input[type='checkbox']
var inputCheckBox = document.createElement("input");
inputCheckBox.setAttribute('type', 'checkbox');
inputCheckBox.setAttribute('id', 'checkboxClass')
// add checkbox to div.
divBox.appendChild(inputCheckBox);
// create text node for divBox and add it to divBox.
var txtNode = document.createTextNode(name);
divBox.appendChild(txtNode)
var sizeDivBox = document.createElement("p");
sizeDivBox.setAttribute('style', 'clear:both; display: inline-block;');
var txtSizeNode = document.createTextNode(size);
sizeDivBox.appendChild(txtSizeNode);
divBox.appendChild(sizeDivBox);
// add divBox to ptag.
ptag.appendChild(divBox);
//ptag.appendChild(divTxt);
// add ptag to top_plugin div.
top_plugin.appendChild(ptag);
}
// if file value is not null, make it blank.
if (name != '')
{
name = '';
}
}
I got the solution for the same problems. Please find below the new code.
function uploadDFiles() {
var file = document.getElementById('_file');
file.click();
try {
file.addEventListener("change", getFileName);
}
catch (e) {
file.attachEvent("onclick", getFileNameOnIE);
alert("Error:: "+e.description);
}
}
function getFileName(event) {
var files = event.target.files;
for (var i = 0, f; f = files[i]; i++) {
var fileName = f.name;
var fileSize = f.size;
var fSize = bytesToSize(fileSize, 2);
displayFileList(fileName, fSize);
}
}
But now I have new problem. This code is not working in IE.For IE i am using attachEvent method and its not working. Please find below the code:
function getFileNameOnIE(event) {
alert(event.type);
var files = event.target;
alert(files.length);
for (var i = 0, f; f = files[i]; i++) {
displayFileList(f.name, f.size);
}
}
Can someone provide me the solution for the same now?
--
Tks
Bharat

Categories