Trying to upload JPG via Javascript and Ajax [duplicate]

4

I've created the following form below on a client's website, so that you can change a user's photo:

<form id="formulario" method="post" enctype="multipart/form-data">
    <div class="blocoCampo">
        <span> Escolher nova foto (dimensões: 50px x 50px; formato: JPG) </span>
        <input type="file" id="imgupload" name="imgupload">
    </div>
    <div class="confirmarTrocaSenha">
        <input type="button" value="" id="btn_troca_foto">
    </div>
</form>

Then I created in the function below (javascript) for it to check the extension and the measurements in Pixels of the file. It should always be 50x50 and JPG:

var _URL = window.URL || window.webkitURL;
$("#imgupload").change(function (e) { // Aqui verifica as dimensões e a extensão do arquivo
    var foto = $('#imgupload').val();
    var extensao = foto.substr(foto.length - 3);
    var file, img;
    if ((file = this.files[0])) {
        img = new Image();
        img.onload = function () {
            if(this.width !== 50){
                alert('Dimensões não permitidas!');
                $("#imgupload").val('');
            }
            else if(this. height !== 50){
                alert('Dimensões não permitidas!');
                $("#imgupload").val('');
            }
            else if(extensao != 'jpg'){
                alert('Extensão não permitida!');
                $("#imgupload").val('');
            }
        };
        img.src = _URL.createObjectURL(file);
    }
});

And below is the function that should host the photo, after it has been uploaded:

$('#btn_troca_foto').click(function(){
    var imgupload = $('#imgupload').val();
    if(imgupload == ''){
        alert("Nenhuma foto selecionada!");
    }
    else{
        $.ajax({
            url: "trocarfoto",
            type: "POST",
            data: { imgupload: imgupload },
            success:function(a){
                alert(a);
                $('.contentLightbox, .bgLightbox').fadeOut();
            }
        });
    }
});

And the trocarphoto link link is in PHP below:

public static function trocaFoto() {
    @mkdir('upload/wt_usuario', 0777);
    $target = "upload/wt_usuario/" . $_SESSION['usuario']['id'] . ".jpg";

    move_uploaded_file($_FILES['imgupload']['tmp_name'], $target);
    echo "Foto de perfil alterada";
}

Everything working, minus the part of the move_uploaded_file function, which should take the file that is in the imgupload input and transfer the directory to the server of my site. >

What is wrong or what may be missing? I know that searching the internet has several ways to do it, but I think it's just missing some details in my code.

Thanks to anyone who can help.

    
asked by anonymous 28.06.2017 / 19:12

1 answer

1

To upload via ajax you need to send the data attached to the form so you need this part of code.

Example:

AJAX:

$.ajax({
        // o teu ficheiro PHP que vai guardar os dados no servidor
        url: 'upload.php',
        type: 'POST',
        // dados do formulário
        data: new FormData($('form')[0]),
        // Diz ao Jquery que não processe os dados ou se preocupe com os dados que são enviados.
        // Tens de obrigatoriamente indicar estes para que os ficheiros não sejam corrompidos!
        cache: false,
        contentType: false,
        processData: false,

        xhr: function() {
            var myXhr = $.ajaxSettings.xhr();
            if (myXhr.upload) {
                // Para veres o progresso do upload adiciona isto
                myXhr.upload.addEventListener('progress', function(e) {
                    if (e.lengthComputable) {
                        $('progress').attr({
                            value: e.loaded,
                            max: e.total,
                        });
                    }
                } , false);
            }
            return myXhr;
        },
         success: function(data)
        {
         alert(data);//Nota que se não indicares qual o tipo de dados que esperas receber de volta, pode dar problemas. 
        }
});

upload.php:

move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/'.$_FILES['file']['name']);
$name = $_FILES['file']['tmp_name'];
echo $name;

If you have any questions, just ask for help, which I will try to help.

    
30.06.2017 / 08:30