使用jQuery进行多文件上传

时间:2010-11-20 16:42:20

标签: jquery file-upload

我试图在表单发布之前允许多个文件上传。我想要的是用户只能看到一个文件上传元素,每次选择一个文件时,都会显示一个包含文件名的新<li>和一个图像/链接,用于从中删除该特定文件采集。有一个jQuery MultiFile插件可以满足我的需求,但我不能让自定义样式按照我想要的方式工作,所以我自己动手。

到目前为止,我有以下代码。它成功添加<li>,使用新选择的文件隐藏文件上传元素,并将空文件上传元素附加到页面以供用户选择新文件。我正在努力适当地管理元素的删除,虽然它并不那么困难,但我一直盯着这一点,现在只是觉得我做错了。我希望其他人可能有一些见解,提示要清理它(即使它更优雅),等等。代码如下。

HTML:

<div id="product-image-area" class="group" style="border-bottom: none; padding-top: 0"> 
    <ul id="photos" class="nobull">    
     <li id="no-product-images-msg" class="" > 
            <%= Html.Image("no-photos.png") %> 
     </li> 
   </ul>
 </div> 
 <div id="upload-area"> 
    <h4 class="st">Upload an image</h4>
    <p class="note">Allowed file types are .gif, .jpg, .jpeg, and .png</p> 
    <p id="file-input" class="st sb"><input class="photo-upload" id="VenuePhotos_0" name="VenuePhotos[]" type="file" /></p> 
 </div>

脚本:

$(function () {
     $('.photo-upload').live('change', function () {
         var fileCount = new Number($(this).parent().children('.photo-upload').length);
         $('#photos').append('<li id="venue_photo_' + (fileCount - 1) + '">' + $(this).val() + '<img title="' + (fileCount - 1) + '" src="/vh/public/images/icon-delete.png" class="delete"  /></li>');
         $(this).parent().append(
             $(this).clone().attr('id', 'VenuePhotos_' + fileCount)
         );
         $(this).hide();
     });
     $('.delete').live('click', function (e) {
         var index = $(e).attr('title');
         $('#file-input').children('.photo-upload').remove('#VenuePhotos_' + index);
         $('#photos').children().remove('#venue_photo_' + index);
     });
});

1 个答案:

答案 0 :(得分:4)

答案是闭包,这是JavaScript最强大的功能之一。其他人的职能are able to access the variables of the enclosing functions

您可以在添加文件输入时绑定删除功能,而不是使用.live和动态生成的ID:

$('.photo-upload').live('change', function () {
     var li = $('<li />').text($(this).val()),
         img = $('<img src="/vh/public/images/icon-delete.png" class="delete" />'),
         input = $(this).clone();

     li.append(img);
     $('#photos').append(li);
     $(this).parent().append(input);
     $(this).hide();

     img.click(function() {
         input.remove();
         li.remove();
     });
 });

在此示例中,删除按钮的click处理程序访问在父函数中获取的jQuery包装器(对于必须删除的两个元素)。