SORU
29 Temmuz 2013, PAZARTESİ


Birisi jQuery Dosya Yükleme eklentisi nasıl açıklayabilir?

DÜZENLEME:

Bu hala yapıyorum bitti ne anlatacağım çok trafik alıyor gibi görünüyor. Ben de sonunda kabul cevabı olan Subrat öğretici, izleyerek eklenti çalışma var. Ancak, DV Dosya Yükleme gerçek bir güçlük ve eğer basit bir dosya upload eklentisi arıyorsanız, Uploadify (teşekkürler CORSAİR!) öneririm. Cevap belirttiği gibi, ticari olmayan kullanım için ücretsiz.

Arka plan

jQuery File Upload blueimp kullanmak için kullanıcıların dosya yüklemesine izin vermek için çalışıyorum.Kutunun dışında mükemmel çalışıyorkurulum yönergeleri takip etmek. Ama aslında pratik olarak web sitemde kullanmak için bir kaç şey yapmak mümkün olmak istiyorum

  • Mevcut mesajlarıma aktarıcı vardır
  • Yüklenen dosyalar için dizin değiştirme

Eklenti için tüm dosyaları kök altında bir klasörde yer alır.

Denedim...

  • Kök içine demo sayfasına taşıyarak ve gerekli komut yollarını güncelleniyor
  • 'Ve' önerdi here 'uploadhandler.php dosya seçenekleri. upload_url upload_dir değiştirme
  • Demo javascript ikinci satırda url değişiyor

Önizleme ve ilerleme çubuğu çalışır, ancak dosyaları yüklemek için başarısız olur ve bu hata konsolu almak gösterir her durumda: Uncaught TypeError: Cannot read property 'files' of undefined. Bu eklenti tüm parçaları zor hata ayıklama için yapıyor nasıl çalıştığını anlamıyorum.

Kod

Demo sayfasında javascript:

$(function () {
'use strict';
// Change this to the location of your server-side upload handler:
var url = 'file_upload/server/php/UploadHandler.php',
    uploadButton = $('<button/>')
        .addClass('btn')
        .prop('disabled', true)
        .text('Processing...')
        .on('click', function () {
            var $this = $(this),
                data = $this.data();
            $this
                .off('click')
                .text('Abort')
                .on('click', function () {
                    $this.remove();
                    data.abort();
                });
            data.submit().always(function () {
                $this.remove();
            });
        });
$('#fileupload').fileupload({
    url: url,
    dataType: 'json',
    autoUpload: false,
    acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i,
    maxFileSize: 5000000, // 5 MB
    // Enable image resizing, except for Android and Opera,
    // which actually support image resizing, but fail to
    // send Blob objects via XHR requests:
    disableImageResize: /Android(?!.*Chrome)|Opera/
        .test(window.navigator.userAgent),
    previewMaxWidth: 100,
    previewMaxHeight: 100,
    previewCrop: true
}).on('fileuploadadd', function (e, data) {
    data.context = $('<div/>').appendTo('#files');
    $.each(data.files, function (index, file) {
        var node = $('<p/>')
                .append($('<span/>').text(file.name));
        if (!index) {
            node
                .append('<br>')
                .append(uploadButton.clone(true).data(data));
        }
        node.appendTo(data.context);
    });
}).on('fileuploadprocessalways', function (e, data) {
    var index = data.index,
        file = data.files[index],
        node = $(data.context.children()[index]);
    if (file.preview) {
        node
            .prepend('<br>')
            .prepend(file.preview);
    }
    if (file.error) {
        node
            .append('<br>')
            .append(file.error);
    }
    if (index   1 === data.files.length) {
        data.context.find('button')
            .text('Upload')
            .prop('disabled', !!data.files.error);
    }
}).on('fileuploadprogressall', function (e, data) {
    var progress = parseInt(data.loaded / data.total * 100, 10);
    $('#progress .bar').css(
        'width',
        progress   '%'
    );
}).on('fileuploaddone', function (e, data) {
    $.each(data.result.files, function (index, file) {
        var link = $('<a>')
            .attr('target', '_blank')
            .prop('href', file.url);
        $(data.context.children()[index])
            .wrap(link);
    });
}).on('fileuploadfail', function (e, data) {
    $.each(data.result.files, function (index, file) {
        var error = $('<span/>').text(file.error);
        $(data.context.children()[index])
            .append('<br>')
            .append(error);
    });
}).prop('disabled', !$.support.fileInput)
    .parent().addClass($.support.fileInput ? undefined : 'disabled');
});


Belgelerin eksikliği beni şaşırttı, değiştirmek için basit bir şey gibi görünüyor. Gerçekten, eğer birisi bunu nasıl açıklayabilir sevinirim.

CEVAP
13 EYLÜL 2013, Cuma


Benzer bir işlevsellik için birkaç gün geriye dönüp baktığımda ve tutorialzine iyi bir öğretici geldi. Burada çalışan bir örnek. Tam öğretici here bulunabilir.

Basit bir form dosya yükleme diyalog tutmak için:

<form id="upload" method="post" action="upload.php" enctype="multipart/form-data">
  <input type="file" name="uploadctl" multiple />
  <ul id="fileList">
    <!-- The file list will be shown here -->
  </ul>
</form>

Ve burada dosya yüklemek için jQuery kodu

$('#upload').fileupload({

  // This function is called when a file is added to the queue
  add: function (e, data) {
    //This area will contain file list and progress information.
    var tpl = $('<li class="working">' 
                '<input type="text" value="0" data-width="48" data-height="48" data-fgColor="#0788a5" data-readOnly="1" data-bgColor="#3e4043" />' 
                '<p></p><span></span></li>' );

    // Append the file name and file size
    tpl.find('p').text(data.files[0].name)
                 .append('<i>'   formatFileSize(data.files[0].size)   '</i>');

    // Add the HTML to the UL element
    data.context = tpl.appendTo(ul);

    // Initialize the knob plugin. This part can be ignored, if you are showing progress in some other way.
    tpl.find('input').knob();

    // Listen for clicks on the cancel icon
    tpl.find('span').click(function(){
      if(tpl.hasClass('working')){
              jqXHR.abort();
      }
      tpl.fadeOut(function(){
              tpl.remove();
      });
    });

    // Automatically upload the file once it is added to the queue
    var jqXHR = data.submit();
  },
  progress: function(e, data){

        // Calculate the completion percentage of the upload
        var progress = parseInt(data.loaded / data.total * 100, 10);

        // Update the hidden input field and trigger a change
        // so that the jQuery knob plugin knows to update the dial
        data.context.find('input').val(progress).change();

        if(progress == 100){
            data.context.removeClass('working');
        }
    }
});
//Helper function for calculation of progress
function formatFileSize(bytes) {
    if (typeof bytes !== 'number') {
        return '';
    }

    if (bytes >= 1000000000) {
        return (bytes / 1000000000).toFixed(2)   ' GB';
    }

    if (bytes >= 1000000) {
        return (bytes / 1000000).toFixed(2)   ' MB';
    }
    return (bytes / 1000).toFixed(2)   ' KB';
}

Ve burada verileri işlemek için PHP kod örneği:

if($_POST) {
    $allowed = array('jpg', 'jpeg');

    if(isset($_FILES['uploadctl']) && $_FILES['uploadctl']['error'] == 0){

        $extension = pathinfo($_FILES['uploadctl']['name'], PATHINFO_EXTENSION);

        if(!in_array(strtolower($extension), $allowed)){
            echo '{"status":"error"}';
            exit;
        }

        if(move_uploaded_file($_FILES['uploadctl']['tmp_name'], "/yourpath/." . $extension)){
            echo '{"status":"success"}';
            exit;
        }
        echo '{"status":"error"}';
    }
    exit();
}

Yukarıdaki kodu herhangi bir varolan form eklenebilir. Bu program otomatik olarak fotoğraf gönderir, ekledi sonra. Bu işlevi değiştirilebilir ve mevcut formu teslim ederken resim gönder.

Gerçek kod ile benim cevabım güncellendi. Kodun orijinal yazarın tüm kredi.

Kaynak: http://tutorialzine.com/2013/05/mini-ajax-file-upload-form/

Bunu Paylaş:
  • Google+
  • E-Posta
Etiketler:

YORUMLAR

SPONSOR VİDEO

Rastgele Yazarlar

  • Joseph Hayhoe

    Joseph Hayho

    20 Mayıs 2010
  • psidot

    psidot

    2 Kasım 2006
  • xXGAMERrs_Xx

    xXGAMERrs_Xx

    31 Temmuz 2014