有人可以解释一下如何实现 jQuery 文件上传插件吗?

2024-07-04

编辑(2019 年 10 月):

6 年过去了,jQuery 文件上传显然仍然让人抓狂。如果您在此处的答案中找不到任何安慰,请尝试搜索NPM https://www.npmjs.com/search?q=file%20upload一个现代的替代方案。我保证,这不值得这么麻烦。

我在之前的编辑中推荐了 Uploadify,但正如评论者指出的那样,他们似乎不再提供免费版本。上传是so无论如何,2013年。


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 the tutorial in the accepted answer. However, jQuery File Upload is a real hassle and if you're looking for a simpler file upload plugin, I would highly recommend [Uploadify](http://www.uploadify.com). As an answer pointed out, it is only free for non-commercial use.

背景

我正在尝试使用 blueimp 的jQuery 文件上传 https://github.com/blueimp/jQuery-File-Upload允许用户上传文件。开箱即用,完美运行,按照设置说明进行操作。但为了在我的网站上实际使用它,我希望能够做几件事:

  • 将上传器包含在我的任何现有页面上
  • 更改上传文件的目录

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

我试过了...

  • 将演示页面移动到根目录并更新必要脚本的路径
  • 按照建议更改 UploadHandler.php 文件中的“upload_dir”和“upload_url”选项here https://github.com/blueimp/jQuery-File-Upload/issues/1190.
  • 更改演示 javascript 第二行中的 URL

在所有情况下,都会显示预览,并且进度条运行,但文件无法上传,并且我在控制台中收到此错误:Uncaught TypeError: Cannot read property 'files' of undefined。我不明白插件的所有部分是如何工作的,这使得调试变得困难。

Code

演示页面中的 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');
});

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

几天前,我一直在寻找类似的功能,并在教程杂志上发现了一个很好的教程。这是一个工作示例。完整教程可以找到here http://tutorialzine.com/2013/05/mini-ajax-file-upload-form/.

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

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

这是上传文件的 jQuery 代码:

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

下面是处理数据的 PHP 代码示例:

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

上面的代码可以添加到任何现有的表单中。添加图像后,该程序会自动上传图像。此功能可以更改,您可以在提交现有表单的同时提交图像。

用实际代码更新了我的答案。所有功劳均归代码原作者所有。

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

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

有人可以解释一下如何实现 jQuery 文件上传插件吗? 的相关文章

  • 从 Summernote 文本区域中提取编辑后的文本

    我的数据库中有一个预设电子邮件列表 感谢您成为会员 感谢您购买产品 它正在路上 之类的 我正在使用 Bootstrap 模式来编辑这些电子邮件 当我单击编辑按钮时 模式会下拉 并填充数据库中的数据 电子邮件名称 主题 正文 我在用将数据传递
  • Bootstrap datepicker — 如何获取其他格式的 toDisplay 和其他格式的 toValue

    很长一段时间以来 我都遇到了麻烦toValue and toDisplay 我需要 并出现在显示屏上以格式显示日期年月日和 u toValue 它与表单一起发送 以便它位于年 月 日格式 我尝试了各种方法 但仍然不起作用 我附上了插件官方页
  • 清除日期时间选择器字段中的值

    我确信这很简单 而且我对 jquery javascript 的理解阻碍了我 但我无法让它工作 我需要做的就是 当单击屏幕上的按钮时 将表单上的一些输入字段清除回原始值 对于除日期时间选择器字段之外的所有字段 这都工作正常 这是定义输入字段
  • 如何从脚本标签中读取 JS 数据?

    我有一个外部文件 假设是 foo js function baz 然后在我的 HTML 中 我使用 script 标签导入它 我希望能够从 script 标签内部获取 JS 字符串 我尝试过jquery的html 以及innerHTML和i
  • val() 不会触发 jQuery 中的change()

    我正在尝试触发change当我使用按钮更改文本框的值时 它会在文本框中发生事件 但它不起作用 查看这把小提琴 https jsfiddle net ergec 9z7h2upc 如果您在文本框中输入内容并单击其他位置 change被触发 但
  • 如果没有所需的值,则将文本框重新聚焦到焦点上

    如果文本框没有所需的值 我将把焦点放回文本框 执行此函数后 文本框不会重新聚焦 然而它正在提醒 alert Must be 1 正确 textbox blur function event if this text 1 event prev
  • 添加 jQuery 监听器会降低浏览器性能吗?

    我有一个应用程序 它通过 Ajax 带来响应 并在每次刷新时创建 5 20 个新的 jQuery 单击侦听器 IE 和 Mozilla 浏览器的使用速度似乎都在变慢 这会显着降低浏览器性能吗 听众能被 释放 吗 补充一下安迪关于现场的说法
  • $.getJSON 和 PHP 文件

    是否可以隐藏 php 文件的名称 document ready function getJSON getdata php function returned data if returned data 1 div wall html use
  • 如何使用文件系统或使用javascript或Jquery进行操作?

    我想使用 Javascript 或 jQuery 进行一些跨浏览器的文件操作 例如 File create File write File read Update Remove delete 可以做以上的事情吗 如果可能的话 我可以从哪里得
  • Rails 未在 ajax 帖子上重新加载会话

    我在使用 jQuery 的 Rails 和 ajax 中遇到了一个非常奇怪的问题 尽管我不认为它特定于 jQuery 我的 Rails 应用程序使用 cookie 会话存储 并且我有一个非常简单的登录 可以在会话中设置用户 ID 如果会话中
  • 忽略页面中的 javascript 语法错误并继续执行脚本

    我为 WordPress 开发插件 它在用户端 主题 使用一些jquery作为jquery插件 问题是 当其他作者制作的其他插件出现 javascript 错误时 我的插件的 javascript 无法执行 最糟糕的是 人们认为我的插件存在
  • 使用 jQuery Toggle 更改 div 文本

    使用时slideToggle 如何更改文本关闭 显示 我做了一个简单的操作 但无法恢复文本更改 这是我所做的 document ready function open click function showpanel slideToggle
  • Jquery Dropzone动态改变POST位置

    我有一个关于 Dropzone js 的问题 我希望能够动态更改帖子 URL 例如 window onload function myDropzone new Dropzone my awesome dropzone url upload
  • 如何禁用已经预订的日期?

    我有一个预订酒店房间的表格 其中有两个字段 称为入住和退房 我在这里使用 jQuery datepicker 预订房间 我不想显示那些已经预订的日期 我已经尝试过这样的 function var excludedCheckInDates C
  • 通过鼠标滚轮按下事件在网站上滚动了多少像素?

    我正在编写一个自定义滚动条并正在捕捉mousewheel事件 我使用它来调整我想要滚动的元素的scrollTop 向下滚动的像素数是否有标准 或者因系统而异 我在最新版本的 Firefox 中显示 114px 许多鼠标驱动程序允许您设置鼠标
  • iPad html5 视频没有控件?

    这让我苦恼了一整天 但我不知道如何让 html5 视频播放器在没有本机控件的情况下工作 我不想要任何控件 但如果我不包含它们 视频似乎不想播放 即使我在下面添加一些 javascript 试图强制它播放 它也适用于 iPhone 和多个浏览
  • Cckeditor 字符限制与 charcount 插件

    我怎么能够prevent用户输入新字符在最大字符之后已达到限制 Ckeditor charcount 插件只是向我显示剩余的字符 我希望它停在 0 处 但它会减去整数 这是我的 html 代码
  • 如何在javascript中使用MD5传输密码

    我弹出一个 jquery 对话框模式框用于登录我的网站 当用户单击登录时 它会向 login php 文件发出一个 post 请求 如下所示 post includes login php user username pass passwo
  • AJAX 调用后使用 jquery 刷新 DOM

    我正在做一个新项目http www hotwirerevealed com http www hotwirerevealed com它显示 识别 hotwire com 上的酒店 输入状态和目的地后 我有一个 javascript 函数 它
  • jQuery keydown 和 :not 带输入

    我正在使用一个小脚本 当按下箭头键时 该脚本会触发页面上的下一个 上一个链接 我试图防止用户在我的搜索输入表单中输入时发生这种情况 也许他们的查询拼写错误并希望使用箭头键来修复 这是我正在处理的内容 var j jQuery noConfl

随机推荐