Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Upload 1 file with onchange twice

Tags:

javascript

I found 1 but in my application.

I have to send file to server from my page but I can do that twice with the same file.

I have cod something like

<div>
  <input type="file" accept=".jpg" id="input" style="display:none" onchange="uploadImage(this)"/>
  <button type="button" id="btn" onclick="bind()">Click here</button> 
</div>

<script>

function bind(){
  document.getElementById('input').click();
}

function uploadImage(el){

  var curFiles = el.files;

  if(curFiles.length != 0) {

    var file = curFiles[0];
    var fileReader = new FileReader();

    fileReader.onload = function (loadedFile) {
      sentToServer(loadedFile);
    }
   fileReader.readAsArrayBuffer(file);
  }
</script>

So, when I press button and choose 1 file, for example, 1.jpg, it uploads. If I again choose it, it wouldn't upload again. But if I choose 2.jpg, new image uploads and sends to the server.

So, what should I do to be possible upload any time my 1.jpg. I need do that if my connection with server lost. But I can`t have another button on my form except that one which choose and send

like image 452
Dred Avatar asked Sep 18 '25 05:09

Dred


1 Answers

Yes this is quite typical, after you select the first time the file 1.jpg in the <input> then the second time the change event is not fired again because the input value didn't change!

It's sufficient to reset the value of the input, add somewhere at the end of your handler: el.value = null

function onChange (event) {
  document.body.append('changed')
  event.target.value = null
}
<input type="file" onchange="onChange(event)" />
like image 190
Luca Faggianelli Avatar answered Sep 19 '25 21:09

Luca Faggianelli