Doubt JS with input type file

Asked

Viewed 122 times

2

Good evening, I need some help on the input part, I have a <input type="file" id="filesend" name="file" multiple/>

how do I make a script that automatically detects when the user puts a file in the input and sends a $_POST['file']; to the upload.php?

  • First, add enctype='multipart/form-data' form, since you want to send to a PHP file. Question: You want to create a form that does not need a input of the kind submit, is that it? The user selects the file and the file is automatically sent without needing a click more?

  • Is already added

  • Yes, I want the file to be automatically sent without the input type Submit

  • Beauty! Add onchange="this.form.Ubmit()" to inputand ready.

2 answers

4


Customer side:

<form enctype="multipart/form-data" action="upload.php" method="POST">
    <input type="file" name="file" onchange="this.form.submit();" id="file"/>  
</form>

From server side use $_FILES as @Wallace Maxters proposes.

1

First, you don’t use $_POST to pick up files. It is used $_FILES.

Second, to upload as soon as you select the file, it can be done with jQuery.

I developed a plugin to make it easier.

Behold:

https://gist.github.com/wallacemaxters/7f29b8c8702d06a2afdf

Quite simply, it can be done like this:

$('#filesend').change(function () {

    if (!$(this).val()) return alert('Selecione um arquivo');

     $(this).ajaxUpload({url: 'testando'});
});
  • On the server side, yes. On the client side, in the form, the attribute method is POST.

  • 1

    I don’t understand what you mean. The variable $_POST that is in your question will not catch the file. Only the variable $_FILES. There are no such variables on the client side.

  • I understand! It is that when he says "input and sends a $_POST['file'];", I understand that he means "submit the form".

  • 1

    Thank you, the two methods work, but I chose Eduardo’s because it is simpler and the application is very large

Browser other questions tagged

You are not signed in. Login or sign up in order to post.