本文介绍了有人可以解释如何实现jQuery文件上传插件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

编辑: 这似乎仍然是流量,所以我会解释我最终做了什么。
我最终得到了按照Subrat的教程工作的插件,这是公认的答案。然而,jQuery文件上传是一个真正的麻烦,如果你正在寻找一个简单的文件上传插件,我会强烈推荐(感谢CORSAIR !)。作为答复指出,它只是免费的非商业用途。

背景



我试图使用blueimp的来允许用户上传文件。按照设置说明,开箱即用。但是要真正在我的网站上使用它,我希望能够做一些事情:


  • 将上传器放在我的任何一个现有网页

  • 更改上传文件的目录



插件的所有文件都位于在根目录下的文件夹中。



我试过了...




  • 将演示页面移动到根目录并更新所需脚本的路径
  • 按照建议更改UploadHandler.php文件中的upload_dir和upload_url选项。

  • 更改演示的第二行中的url javascript



在所有情况下,预览显示和进度条都会运行,但文件无法上传,并在控制台中出现此错误: code> Uncaught TypeError:无法读取未定义的属性'文件'。
$ b

代码



演示页面中的javascript:

  $(function(){
'use strict';
//将其更改为服务器端上传处理程序的位置:
var url ='file_upload / server / php / UploadHandler.php',$ b $ 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,$ b $ acceptFileTypes: \\。/ \\ /(gif | jpe?g | png)$ / i,
maxFileSize:5000000,// 5 MB
//启用图片大小调整,Android和Opera除外
//实际上支持图片大小调整,但不能
//通过XHR请求发送Blob对象:
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){
$ b .append($('< span />')。text(file.name));
if(!索引){
节点
.append('< br>')
.a PPEND(uploadButton.clone(真)。数据(数据));
}
node.appendTo(data.context);
}); (b,b,b,b,b, $(data.context.children()[index]);
if(file.preview){
node
.prepend('< br>')
.prepend (file.preview);
}
if(file.error){
node
.append('< br>')
.append(file。错误);
}
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 +' ('fileuploaddone',function(e,data){
$ .each(data.result.files,f (index,file){
var link = $('< a>)
.attr('target','_blank')
.prop('href',file .URL);
$(data.context.children()[index])
.wrap(link);
});函数(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');
});



我对缺乏文档感到惊讶,应该是一个简单的事情来改变。我真的很感激,如果有人可以解释如何做到这一点。

解决方案

我有些时候正在寻找类似的功能,在tutorialzine的一个很好的教程。这是一个工作的例子。完整的教程可以在找到。



简单形式保存文件上传对话:

 < form id =uploadmethod =post action =upload.phpenctype =multipart / form-data> 
< input type =filename =uploadctlmultiple />
< ul id =fileList>
< / ul>
< / form>

这里是上传文件的jQuery代码:

  $('#upload')。fileupload({

//当将文件添加到队列中时调用此函数
add:function(e,data){
//这个区域将包含文件列表和进度信息
var tpl = $('< li class =working>'+ $ b data-bgColor =data-width =#0788a5data-fgColor =0data-width =48data-height =48 #3e4043/>'+
'< p>< / p>< span>< / span>< / li>');

//追加(data.files [0] .name)
.append('< i>'格式文件大小(data.files [ 0] .size)+'< / i>');

//将HTML添加到UL元素
data.context = tpl.appendTo(ul);

//初始化旋钮插件,如果你这个部分可以忽略正在以其他方式显示进展。
tpl.find('input')。knob();

//听取点击取消图标
tpl.find('span')。click(function(){
if(tpl.hasClass('working')) ){
jqXHR.abort();
}
tpl.fadeOut(function(){
tpl.remove();
});
});

//将文件添加到队列后自动上传文件
var jqXHR = data.submit();
},
progress:function(e,data){

//计算上传完成百分比
var progress = parseInt(data.loaded / data总计* 100,10);

//更新隐藏的输入字段并触发更改
//以便jQuery旋钮插件知道更新拨号
data.context.find('input') .VAL(进度).change();

if(progress == 100){
data.context.removeClass('working');
}
}
});
//用于计算进度的辅助函数
函数formatFileSize(bytes){
if(typeof bytes!=='number'){
return''; (字节> = 1000000000){
return(bytes / 1000000000).toFixed(2)+'GB';
}

if (字节> = 1000000){
return(bytes / 1000000).toFixed(2)+'MB';
}

if

return(bytes / 1000).toFixed(2)+'KB';



$ b $ p
$ b

这里是处理数据的PHP代码示例:



pre $ if($ _ POST){
$ allowed = array('jpg','jpeg');

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

$ extension = pathinfo($ _ FILES ['uploadctl'] ['name'],PATHINFO_EXTENSION);
$ b $ if(!in_array(strtolower($ extension),$ allowed)){
echo'{status:error}';
出口;

$ b $ if(move_uploaded_file($ _ FILES ['uploadctl'] ['tmp_name'],/ yourpath /。。$ extension)){
echo'{状态 : 成功};
出口;
}
echo'{status:error}';
}
exit();

code $


上面的代码可以添加到任何现有的表单中。这个程序一旦添加就自动上传图像。这个功能可以改变,你可以提交图像,而你正在提交你的现有表单。



更新我的答案与实际的代码。所有学分原始作者的代码。



来源:


EDIT:

This still seems to be getting traffic so I'll explain what I ended up doing. I eventually got the plugin working by following Subrat's tutorial, which is the accepted answer. However, jQuery File Upload is a real hassle and if you're looking for a simple file upload plugin, I would highly recommend Uploadify (thanks CORSAIR!). As an answer pointed out, it is only free for non-commercial use.

Background

I'm trying to use blueimp's jQuery File Upload to allow users to upload files. Out of the box it works perfectly, following the setup instructions. But to actually use it practically on my website, I want to be able to do a couple things:

  • Include the uploader on any of my existing pages
  • Change the directory for uploaded files

All the files for the plugin are located in a folder under the root.

I've tried...

  • Moving the demo page into the root and updating the paths for the necessary scripts
  • Changing the 'upload_dir' and 'upload_url' options in the UploadHandler.php file as suggested here.
  • Changing the url in the second line of the demo javascript

In all cases the preview shows and the progress bar runs, but the files fails to upload and I get this error in the console: Uncaught TypeError: Cannot read property 'files' of undefined. I don't understand how all the parts of the plugin work which is making it difficult to debug.

Code

The javascript in the demo page:

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


I'm surprised by the lack of documentation, it seems like it should be a simple thing to change. I would really appreciate if someone could explain how to do this.

解决方案

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/

这篇关于有人可以解释如何实现jQuery文件上传插件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 20:47