Ajax yordamida Sahifani qayta yuklamasdan serverga fayl yuklash

+3 ovoz
72 marta ko‘rilgan
so‘radi 25 iyul, 17 Farhodjon (1,013 bal)
Assalomu alaykum. Men serverga ajax yordamida fayl yuklamoqchi edim. Buni qanday qilsam boladi?

4 Javoblar

+1 ovoz
javob berdi 25 iyul, 17 SedBigDaddy (1,232 bal)
tanlangan 25 iyul, 17 Farhodjon
 
Eng yaxshi javob
var data = new FormData();
jQuery.each(jQuery('#logo_file')[0].files, function(i, file) {
    data.append('avatar', file);
});
$.ajax({
    // url: '/controller/upload_user_ava.php',
    url: '/save-avatar',
    type: 'POST',
    data: data,
    cache: false,
    contentType: false,
    processData: false,
    success: function(res) {
       //code
    },
    error: function(e) {
       //code
    }
});
0 ovoz
javob berdi 25 iyul, 17 Farhodjon (1,013 bal)
<form action='upload.php' enctype='multipart/form-data' id='uploadForm'>

<input type='file' name='file' id='user-img'>

</form>

<span class='uploading'></span>

JQUERY

$('#users-img').on('change', function(e) {

e.preventDefault();

$('#uploadForm').submit();

$('#uploadForm').on('submit', function(e) {

e.preventDefault();

$.ajax({

url: $(this).attr('action'),

data: new FormData(this),

type: 'POST',

contentType: false,

cache: false,

processData: false,

beforeSend: function() {

$('.uploading').html('Uploading...');

},

success: function(res) {

if (res == 1) {

$('.uploading').html('');

}

}

});

});

});
izoh qoldirdi 25 iyul, 17 Farhodjon (1,013 bal)
Shu kodlar ishladi
0 ovoz
javob berdi 25 iyul, 17 Clever (169 bal)

shu linklani bir ko'rib chiqingchi balki foydasi tegib qolar:

1) https://abandon.ie/notebook/simple-file-uploads-using-jquery-ajax

2) https://code.tutsplus.com/tutorials/uploading-files-with-ajax--net-21077

EDIT:

shahsan manda imageni yukashni qilingan (chiroyli kode emas lekin tushinish uchun yetarli deb o'ylayman):

$(function () {
        $(":file").change(function () {
            if (this.files && this.files[0]) {
                var reader = new FileReader();
                var file1 = this.files[0];

                var $input = $("#imgupl");
                var fd = new FormData;

                fd.append('img', $input.prop('files')[0]);

                $.ajax({
                    // url: '/controller/upload_user_ava.php',
                     url: '/save-avatar',
                     type: 'POST',
                     data: fd,
                     cache: false,
                     contentType: false,
                     processData: false,
                     success: function(res) {
                        console.log(res);
                        // reader.onload = imageIsLoaded;
                        reader.onload = function() {
                            $('#myImg').attr('src', this.result);
                        };
                        window.location.reload(true);
                        //reader.readAsDataURL(file1);
                     },
                     error: function(e) {
                        console.log(e);
                     }
                });
            }
        });
    });

php:

<?php

if(isset($_SESSION["id"])){
    // $uploadfile = $_SERVER['DOCUMENT_ROOT'].'/ava/'.$_SESSION["id"].'.png';
    $target_dir = 'ava/';
    $target_file = $target_dir . basename($_FILES["img"]["name"]);
    $imageFileType = pathinfo($target_file, PATHINFO_EXTENSION);
    
    // Check if image file is a actual image or fake image
    $check = getimagesize($_FILES["img"]["tmp_name"]);
    if($check === false) {
        echo "File is not an image.";
        exit;
    }

    // Check file size
    if ($_FILES["img"]["size"] > 2048000) {
        echo "Sorry, your file is too large.";
        exit;
    }
    // Allow certain file formats
    if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif" ) {
        echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
        exit;
    }

    $upload_file = $target_dir.$_SESSION['id'].'.'.$imageFileType;
    // echo $upload_file; exit;
    if (move_uploaded_file($_FILES["img"]["tmp_name"], $upload_file)) {
        $user = Users::find($_SESSION['id']);
        $user->avatar = $_SESSION['id'].'.'.$imageFileType;
        if ($user->save()) {
            //require_once '../admin/img_upload.php';
            //resize($upload_file, $upload_file, 300, 300); // anti shell :-) resize image to 300x300
            echo 'ok';
            exit;
        } else {
            echo 'User model is not saved';
            exit;
        }
    }

    echo 'Изображение не загружено';
    exit;
}

0 ovoz
javob berdi 25 iyul, 17 Sardor Dushamov (1,527 bal)
Yii2 frameworkni ham tag qilibsiz va yii2 da qilyapsiz deb o'yladim.

Yii2 ni o'zini dokumentatsiyasida juda tushunarli qilib misol bilan tushuntirgan.

http://www.yiiframework.com/doc-2.0/guide-input-file-upload.html
izoh qoldirdi 25 iyul, 17 Farhodjon (1,013 bal)
Ha manda ham Yii2 da. Bu yerda asosiy etibor JQueryga qaratilganda shuning uchun qisqaroq yozdim.

Assalomu alaykum, yordam.uz saytimizga xush kelibsiz.

Bu saytda o`zingizni qiziqtirgan savollarga javob olishingiz va o`z sohangiz bo`yicha savollarga javob berishingiz mumkin.

Bizning Oilamizga a'zo bo`lganingiz uchun chuqur Minnatdorchilik bildiramiz !!!

Telegram kanal YordamUzRss

...