upload without refresh with Formdata, jquery

Asked

Viewed 3,152 times

10

I need to update my script and I want to adapt my upload formats to be upados without the need to refresh. I didn’t enjoy using third party script so I researched and came across this function of jQuery FormData .

I didn’t quite understand what I read so I came here to ask for a support...

How to send files to the server (PHP) using Ajax and Formdata?

Thank you.

  • There is also a way to upload or post, without refresh, through an iframe that in the case is placed as target. Behold

1 answer

7


I use the jQuery, no plugin, so you can upload files.

I will illustrate in a very simplified way:

index php.

<script src="jquery.js"></script>

<script>
$(function()
{
    $('form').submit(function(e)
    {
        e.preventDefault();

        var formData = new FormData();

        formData.append('image', $('#file').prop('files')[0]);

          $.ajax({
            url: 'upload.php',
            data: formData,
            type: 'post',
            success: function(response)
            {
                console.log(response)
            },
            processData: false,
            cache: false,
            contentType: false
          });
    });
});
</script>

<form method="post" enctype="multipart/form-data">
    <input type="file" id="file" />
    <input type="submit" />
</form>

upload.php

if (move_uploaded_file($_FILES['image']['tmp_name'], $novo_nome)) {
     echo json_encode($_FILES);
}

Data must be sent via post by Ajax and, in the form, configure it as enctype="Multipart/form-data"

  • How to choose where to store the file?

  • When you set a name for the file that will save, you also set along with it the folder. Example: I want to save the upload as foto.jpg then do $novo_nome = "pasta/a/salvar/foto.jpg".

  • @Wallance Maxters, thanks for your help. You know how to do in jquery to check if imput file has been selected some file to start uploading automatically?

  • 1

    I searched a lot for something like this. Your solution was the best. No plugin, simple, practical and objective. I thank you very much. =)

Browser other questions tagged

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