I am creating a script to upload XML-files to a server, where you enter how often specific tags occur in the file. Now I wanted to automate this, so that i check the XML-file befor uploading, so that the previous manually entered fields are filled automaticly.
I just dont get the point how i can get the content of the file befor actually uploading it - i want to use Javascript for the check and auto-fillment.
The upload is completly realized in php.
Someone have an idea for me?
Edit:
var fileInput;
window.onload = function() {
fileInput = document.getElementById('file_input');
};
function getNodes() {
var anzNodes = fileInput.getElementsByTagName("node").length;
return anzNodes;
}
function getEdges() {
var anzEdges = fileInput.getElementsByTagName("edge").length;
return anzEdges;
}
function fillForm() {
document.getElementById("nodes").value = getNodes();
document.getElementById("edges").value = getEdges();
}
So I have a html-form with the ID file_input. I try to grab that file (which is XML) befor uploading, search it for the amount of "node" and "edge" tags, and autofill these information into the html form. This should happen when the file is chosen. Is this better?
Use the FileReader functionality in JavaScript to grab the document before uploading it. Then you can read the text of the file and pre-process it before sending it to the server.
I found the answer and will provide it for completeness.
My Javascript part:
var openFile = function (event) {
var input = event.target;
var reader = new FileReader();
reader.onload = function () {
var anzEdges = (reader.result.match(/<edge/g) || []).length;
var anzNodes = (reader.result.match(/<node/g) || []).length;
document.getElementById("nodes").value = anzNodes;
document.getElementById("edges").value = anzEdges;
};
reader.readAsText(input.files[0]);
};
and the relevant html-code:
<input type="file" onchange="openFile(event)" name="file_upload" size="60"><br>
<input type="number" id="nodes" name="nodes" min="2" readonly><br>
<input type="number" id="edges" name="edges" min="1" readonly>
Related
I am new to JavaScript, not sure if this very basic question. I've created a Bitcoin Price update dashboard using the data fetched from the external WebSocket. I managed to get the data from the WebSocket and display it on the console tab and display the data in a h1 tag. The price updates every seconds. Now i need to show the price in a html field. i tried but it's kinda hard for me.
I have provided the code snippets below as well as external Websocket from where I am pulling the data.
Please let me know how should I insert the row dynamically into a HTML input field. Thank you so much in advance
<input type="text" class="form-control" id="btcpricenow" readonly>
<script>
var priceSocket = new WebSocket("wss://stream.binance.com:9443/ws/btcusdt#trade"),
liveprice = document.getElementById("btcpricenow");
priceSocket.onmessage = function (event) {
var liveprice = JSON.parse(event.data);
liveprice.innerText = parseFloat(liveprice.p).toFixed(2);
}
</script>
You set liveprice to be the HTML element, and then reset it inside your function to be the parsed event.data. Don't reset the variable like that, just set a new variable instead. Also, when you are putting a value inside an input element use value, not innerHTML
<input type="text" class="form-control" id="btcpricenow" readonly>
<script>
let priceSocket = new WebSocket("wss://stream.binance.com:9443/ws/btcusdt#trade"),
liveprice = document.getElementById("btcpricenow");
priceSocket.onmessage = function(event) {
let data = JSON.parse(event.data);
liveprice.value = parseFloat(data.p).toFixed(2);
}
</script>
use this :
const data= JSON.parse(event.data);
let liveprice = document.getElementById("btcpricenow");
liveprice.value = parseFloat(data.p).toFixed(2) || "";
Is there any chance to detect every file selection the user made for an HTML input of type file element?
This was asked many times before, but the usually proposed onchange event doesn't fire if the user select the same file again.
Set the value of the input to null on each onclick event. This will reset the input's value and trigger the onchange event even if the same path is selected.
var input = document.getElementsByTagName('input')[0];
input.onclick = function () {
this.value = null;
};
input.onchange = function () {
console.log(this.value);
};
<input type="file" value="C:\fakepath">
Note: It's normal if your file is prefixed with 'C:\fakepath'. That's a security feature preventing JavaScript from knowing the file's absolute path. The browser still knows it internally.
Use onClick event to clear value of target input, each time user clicks on field. This ensures that the onChange event will be triggered for the same file as well. Worked for me :)
onInputClick = (event) => {
event.target.value = ''
}
<input type="file" onChange={onFileChanged} onClick={onInputClick} />
Using TypeScript
onInputClick = ( event: React.MouseEvent<HTMLInputElement, MouseEvent>) => {
const element = event.target as HTMLInputElement
element.value = ''
}
<form enctype='multipart/form-data'>
<input onchange="alert(this.value); this.value=null; return false;" type='file'>
<br>
<input type='submit' value='Upload'>
</form>
this.value=null; is only necessary for Chrome, Firefox will work fine just with return false;
Here is a FIDDLE
In this article, under the title "Using form input for selecting"
http://www.html5rocks.com/en/tutorials/file/dndfiles/
<input type="file" id="files" name="files[]" multiple />
<script>
function handleFileSelect(evt) {
var files = evt.target.files; // FileList object
// files is a FileList of File objects. List some properties.
var output = [];
for (var i = 0, f; f = files[i]; i++) {
// Code to execute for every file selected
}
// Code to execute after that
}
document.getElementById('files').addEventListener('change',
handleFileSelect,
false);
</script>
It adds an event listener to 'change', but I tested it and it triggers even if you choose the same file and not if you cancel.
handleChange({target}) {
const files = target.files
target.value = ''
}
<input #myInput type="file" id="imgFile" (click)="$event.target.value=null"
(change)="detectUploadedImage($event)" accept="image/*" />
Clearing the value of 0th index of input worked for me. Please try the below code, hope this will work (AngularJs).
scope.onClick = function() {
input[0].value = "";
input.click();
};
Usage of two way binding worked for me if you are working with Angular.
Here is my HMTL
<input type="file" #upload name="upload" [(ngModel)]="inputValue"(change)='fileEvent($event)'/>
and TS..
#ViewChild('upload') uploadBtn: HTMLElement;
fileEvent(e: any){
//file upload part...
this.inputValue = "";
}
The selected answer (using state to set input value null) gave me an error.
I use empty strings instead
const [fileValue, setFileValue] = React.useState("")
<input
onClick={() => {
setFileValue("");
}}
type="file"
value={fileValue}
onChange={handleAddFile}
/>
Do whatever you want to do after the file loads successfully.just after the completion of your file processing set the value of file control to blank string.so the .change() will always be called even the file name changes or not. like for example you can do this thing and worked for me like charm
$('#myFile').change(function () {
LoadFile("myFile");//function to do processing of file.
$('#myFile').val('');// set the value to empty of myfile control.
});
I've got an issue with my uploads,
I'm using FileReader with readAsDataURL() method, when user select its images then he can preview files.
Also I have a button which has classname "del-first", when user click on it first image should be deleted from preview and also from input value. That's my problem.
So I have an input:
<form method="post" enctype="multipart/form-data">
<input type="file" id="myFiles" name="myFiles[]" accept="image/png, image/jpeg" multiple />
<div class="preview-wrapper">
<button class="del-first"></button>
</div>
<input type="submit" value="SUBMIT" />
</form>
My Javscript:
const fileInput = document.getElementById("myFiles");
function previewFiles() {
var preview = document.querySelector('.preview-wrapper');
var files = fileInput.files;
function readAndPreview(file) {
// Make sure `file.name` matches our extensions criteria
if ( /\.(jpe?g|png|gif)$/i.test(file.name) ) {
var reader = new FileReader();
reader.addEventListener("load", function() {
var conta = document.createElement('div');
conta.className = "preview-image";
var image = new Image();
image.height = 100;
image.title = file.name;
image.src = this.result;
conta.appendChild( image );
preview.appendChild( conta );
}, false);
reader.readAsDataURL(file);
}
}
if (files) {
[].forEach.call(files, readAndPreview);
}
var newFileList = Array.from(event.target.files);
console.log(newFileList);
var imgRemove = document.querySelector('.del-first');
imgRemove.addEventListener("click", function(e) {
e.preventDefault();
newFileList.splice(0,1);
console.log(newFileList);
})
}
fileInput.addEventListener("change", previewFiles);
As you can see in the end of the script I used array.from for my files:
var newFileList = Array.from(event.target.files);
then I added listener, when user click button first object should be deleted:
var imgRemove = document.querySelector('.del-first');
imgRemove.addEventListener("click", function(e) {
e.preventDefault();
newFileList.splice(0,1);
console.log(newFileList);
})
So in my console.log I'm getting that it has been deleted, but now I need somehow push my newFileList to my input, so when user click submit I get on my server valid files. But I don't know how to make it?
According to my understanding, I don't think you could remove the file from your file list. The file's data in files is read-only, so I recommend you use multiple <input type="file"> for adding file instead of <input type="file" multiple>, so that you can easily remove the specific file with the simple remove button (clear the value of the file input). It may be inconvenient for the user, but it works in your case I think.
========Update
Instead of using <input type="file" multiple>. You can use the alternative way like this. You can take a look of this
Hope it would help. Please correct me if I were wrong
I was looking for a solution though there are many answers on the same topics I was unable to figure out the problem in my code.
The problem is, I can only read the first file input using this API.
The last two inputs show undefined if I console.log(e.target.files[1]);
I am using vue 2. Here is the codes I have.
For the three inputs I have
<input type="file" name="file[]" #change="img1">
<input type="file" name="file[]" #change="img2">
<input type="file" name="file[]" #change="img3">
img1(e){
console.log(e.target.files[0]);
this.readFile(e,'img1',0);
},
img2(e){
console.log(e.target.files[1]);
this.readFile(e,'img2',1);
},
img3(e){
console.log(e.target.files[2]);
this.readFile(e,'img3',2);
},
Here is my readFile method
readFile(e,img,i) {
let self=this;
if(window.FileReader) {
var file = e.target.files[i];
var reader = new FileReader();
if (file) {
let type=e.target.files[i].type;
console.log(type);
if(!this.cheackType(type)){
this.showTypeWarn('Invalid Image Formate', 'Please Upload jpg or a png file only');
return
}
reader.readAsDataURL(file);
} else {
// img.css('display', 'none');
// img.attr('src', '');
}
reader.onloadend = function (e) {
self.data.img=reader.result;
}
}
}
Thank you.
When you do console.log(e.target.files[i]); you are accessing the i-th file of the element that fired the event. You should try with console.log(e.target.files[0]); to access the first file of each input.
I want to get the filename of a file user selected when a user clicks on a button it is not a submit button. I have tried many of the solutions given on stackoverflow but it does not work i have id of the field but it does not give the name of the file.
Below is my code:
function Data(a)
{
var ext = $('#fieldid_'+a).val().split('.').pop().toLowerCase();
.......
<input type="file" name="save_<?=$row1['id']?>" id="fieldid_<?=$row1['id']?>" />
<input type="button" id="submit_<?=$row1['id']?>" value="Upload File" onclick = "return Data(<?=$row1['id']?>)"/>
Use the below script to get the file name:
Reference Link:Use jQuery to get the file input's selected filename without the path
jQuery('input[type=file]')[0].files[0].name
(OR)
$('input[type=file]')[0].files[0].name
For more than on file:
var all_files = jQuery('input[type=file]');
var paths_arr = [];
for(var i=0;i<all_files.length;i++){
paths_arr.push(all_files[i].files[0].name);
}
paths_arr[0] = first file name
paths_arr[1] = second file name
document.getElementById('fileInputId').files[0].name
see fiddle
Files is the FileList object & names is an Array of strings (file names)
$( "#buttonid_1" ).click(function(){
var files = $('#fieldid_1').prop("files");
var names = $.map(files, function(val){
return val.name;
});
console.log(names[0]);
})
Reference: https://stackoverflow.com/a/10703223/3119231
Example: http://jsfiddle.net/ndfn782o/1/
EDIT: tested && 110% working