Can someone explain how to implement the jQuery File Upload plugin?

前端 未结 10 529
一向
一向 2020-12-02 04:44

EDIT (Oct 2019):

6 years later and jQuery File Upload is clearly still driving folks insane. If you\'re finding little solace in the answers here, try a se
相关标签:
10条回答
  • 2020-12-02 05:07

    You can use uploadify this is the best multiupload jquery plugin i have used.

    The implementation is easy, the browser support is perfect.

    0 讨论(0)
  • 2020-12-02 05:09

    I was looking for a similar functionality some days back and came across a good tutorial on tutorialzine. Here is an working example. Complete tutorial can be found here.

    Simple form to hold the file upload dialogue:

    <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>
    

    And here is the jQuery code to upload the files:

    $('#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';
    }
    

    And here is the PHP code sample to process the data:

    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();
    }
    

    The above code can be added to any existing form. This program automatically uploads images, once they are added. This functionality can be changed and you can submit the image, while you are submitting your existing form.

    Updated my answer with actual code. All credits to original author of the code.

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

    0 讨论(0)
  • 2020-12-02 05:15

    Droply.js is perfect for this. It's simple and comes pre-packaged with a demo site that works out of the box.

    0 讨论(0)
  • 2020-12-02 05:19

    Check out the Image drag and drop uploader with image preview using dropper jquery plugin.

    HTML

    <div class="target" width="78" height="100"><img /></div>
    

    JS

    $(".target").dropper({
        action: "upload.php",
    
    }).on("start.dropper", onStart);
    function onStart(e, files){
    console.log(files[0]);
    
        image_preview(files[0].file).then(function(res){
    $('.dropper-dropzone').empty();
    //$('.dropper-dropzone').css("background-image",res.data);
     $('#imgPreview').remove();        
    $('.dropper-dropzone').append('<img id="imgPreview"/><span style="display:none">Drag and drop files or click to select</span>');
    var widthImg=$('.dropper-dropzone').attr('width');
            $('#imgPreview').attr({width:widthImg});
        $('#imgPreview').attr({src:res.data});
    
        })
    
    }
    
    function image_preview(file){
        var def = new $.Deferred();
        var imgURL = '';
        if (file.type.match('image.*')) {
            //create object url support
            var URL = window.URL || window.webkitURL;
            if (URL !== undefined) {
                imgURL = URL.createObjectURL(file);
                URL.revokeObjectURL(file);
                def.resolve({status: 200, message: 'OK', data:imgURL, error: {}});
            }
            //file reader support
            else if(window.File && window.FileReader)
            {
                var reader = new FileReader();
                reader.readAsDataURL(file);
                reader.onloadend = function () {
                    imgURL = reader.result;
                    def.resolve({status: 200, message: 'OK', data:imgURL, error: {}});
                }
            }
            else {
                def.reject({status: 1001, message: 'File uploader not supported', data:imgURL, error: {}});
            }
        }
        else
            def.reject({status: 1002, message: 'File type not supported', error: {}});
        return def.promise();
    }
    
    $('.dropper-dropzone').mouseenter(function() {
     $( '.dropper-dropzone>span' ).css("display", "block");
    });
    
    $('.dropper-dropzone').mouseleave(function() {
     $( '.dropper-dropzone>span' ).css("display", "none");
    });
    

    CSS

    .dropper-dropzone{
        width:78px;
    padding:3px;
        height:100px;
    position: relative;
    }
    .dropper-dropzone>img{
        width:78px;
        height:100px;
    margin-top=0;
    }
    
    .dropper-dropzone>span {
        position: absolute;
        right: 10px;
        top: 20px;
    color:#ccc;
    
    
    }
    
    .dropper .dropper-dropzone{
    
    padding:3px !important    
    }
    

    Demo Jsfiddle

    0 讨论(0)
提交回复
热议问题