asp.net+swfupload 多图片批量上传(附源码下载)

时间:2022-08-29 08:15:24

asp.net的文件上传都是单个文件上传方式,无法执行一次性多张图片批量上传操作,要实现多图片批量上传需要借助于flash,通过flash选取多个图片(文件),然后再通过后端服务进行上传操作.

本次教程所使用的flash上传文件是 swfupload,下面会有源码下载链接。

使用工具 vs 2010。

演示效果图

asp.net+swfupload 多图片批量上传(附源码下载)asp.net+swfupload 多图片批量上传(附源码下载)

asp.net+swfupload 多图片批量上传(附源码下载)

第一步 新建一个web项目

asp.net+swfupload 多图片批量上传(附源码下载)

第二步 引入所需swfuplod文件(swfupload.swf,js,css等)

asp.net+swfupload 多图片批量上传(附源码下载)

 

第三步 新建一个一般处理程序(upload.ashx)

asp.net+swfupload 多图片批量上传(附源码下载)

upload.ashx程序文件代码

using System;
using System.Collections.Generic;
using System.Web;
using System.IO;
 
namespace yuyue.upload
{
 /// <summary>
 /// upload 的摘要说明
 /// </summary>
 public class upload : IHttpHandler
 {
 
   public void ProcessRequest(HttpContext context)
   {
      context.Response.ContentType = "text/plain";
      try
      {
         HttpPostedFile file;
             for (int i = 0; i < context.Request.Files.Count; ++i)
             {
                file = context.Request.Files[i];
                if (file == null || file.ContentLength == 0 || string.IsNullOrEmpty(file.FileName)) continue;
                string filename = DateTime.Now.ToString("yyyyMMddHHmmss") + RndNumStr(6) + Path.GetExtension(file.FileName); //文件名=上传日期+随机字符串+扩展名(可避免多人上传是第一名问题)
 
                /********************文件夹**************************/
                string year=DateTime.Now.Year.ToString();
                string monthday = DateTime.Now.ToString("MMdd");
 
               if (!Directory.Exists(HttpContext.Current.Server.MapPath("/uploads/")+year))
               {
                   Directory.CreateDirectory(HttpContext.Current.Server.MapPath("/uploads/") + year);
               }
               if (!Directory.Exists(HttpContext.Current.Server.MapPath("/uploads/") + year + "/" + monthday))
               {
                   Directory.CreateDirectory(HttpContext.Current.Server.MapPath("/uploads/") + year + "/" + monthday);
               }
               file.SaveAs(HttpContext.Current.Server.MapPath("/uploads/" + year + "/" + monthday + "/" + filename));
               context.Response.Write("/uploads/" + year + "/" + monthday + "/" + filename);//输出上传地址以用于前台js获取
 
            }
        }
        catch (Exception ex)
        {
           context.Response.StatusCode = 500;
           context.Response.Write(ex.Message);
           context.Response.End();
        }
        finally
        {
           context.Response.End();
        }
 }
 
 #region 该方法用于生成指定位数的随机字符串
 /// <summary>
 /// 该方法用于生成指定位数的随机字符串
 /// </summary>
 /// <param name="VcodeNum">参数是随机数的位数</param>
 /// <returns>返回一个随机数字符串</returns>
 public static string RndNumStr(int VcodeNum)
 {
      string[] source = { "0", "1", "1", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z" };
 
      string checkCode = String.Empty;
      Random random = new Random();
      for (int i = 0; i < VcodeNum; i++)
      {
         checkCode += source[random.Next(0, source.Length)];
      }
      return checkCode;
 }
 #endregion
 
 public bool IsReusable
 {
    get
    {
      return false;
    }
 }
 }
}

第四步 新建一个web窗体(swfupload.aspx)

asp.net+swfupload 多图片批量上传(附源码下载)

swfupload.aspx 文件源码

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="swfupload.aspx.cs" Inherits="yuyue.upload.swfupload" %>
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
 <title>文件上传</title>
 <link href="/statics/js/swfupload/css.css" rel="stylesheet" type="text/css" />
 <script type="text/javascript" src="/statics/js/jquery-1.7.2.min.js"></script>
 <script type="text/javascript" src="/statics/js/swfupload/swfupload.js"></script>
 <script type="text/javascript" src="/statics/js/swfupload/swfupload.queue.js"></script>
 <script type="text/javascript" src="/statics/js/swfupload/fileprogress.js"></script>
 <script type="text/javascript" src="/statics/js/swfupload/filegroupprogress.js"></script>
 <script type="text/javascript" src="/statics/js/swfupload/handlers.js"></script>
 <asp:Literal ID="Literal1" runat="server"></asp:Literal>
 
 <script type="text/javascript">
 function album_cancel(obj,src) {
 $(obj).toggleClass("on");
 if ($(obj).hasClass("on")) {
 $("#tb_imgurls").val($("#tb_imgurls").val() + src);
 $("#piclists").val($("#piclists").val() + "<li><a href=\"" + src.toString().substring(0, src.length - 1) + "\" title=\"点击图片查看大图\" onclick=\"return hs.expand(this)\"><img src='" + src.toString().substring(0, src.length - 1) + "' width='86' height='80' alt='点击图片查看大图'></a></li>");
 }
 else {
 var str = $("#tb_imgurls").val();
 var strpic = $("#piclists").val();
 $("#tb_imgurls").val(str.replace(src, ''));
 $("#piclists").val(strpic.replace("<li><a href=\"" + src.toString().substring(0, src.length - 1) + "\" title=\"点击图片查看大图\" onclick=\"return hs.expand(this)\"><img src='" + src.toString().substring(0, src.length - 1) + "' width='86' height='80' alt='点击图片查看大图'></a></li>", ""));
 }
 }
 
 function confirmupload() {
 parent.$("#relaimg").val(parent.$("#relaimg").val()+$("#tb_imgurls").val());
 parent.$(".piclist").html(parent.$(".piclist").html() + $("#piclists").val());
 parent.TB_remove();
 }
 
 </script>
 
</head>
<body>
 <form name="frmMain" method="post" action="upload.ashx" id="frmMain" enctype="multipart/form-data">
<div>
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwULLTE0MDkxNzYwNDNkZITPwV8CB9intILgmCGmWeJNXndY" />
</div>
 <table cellpadding="5">
 <tr>
 <td style="padding:5px;"><span id="spanButtonPlaceHolder"></span></td>
 <td style="padding:5px;"><span class="btn_upload" onclick='swfu.startUpload()'><img src="/statics/js/swfupload/images/swfBnt_upload.png" /></span></td>
 <td style="padding:5px;"><div id="nameTip" class="onShow">最多上传<font color="red"> <asp:Literal ID="Literal2" runat="server"></asp:Literal></font> 个附件,单文件最大 <font color="red"><asp:Literal ID="Literal3" runat="server"></asp:Literal></font></div></td>
 </tr>
 <tr>
 <td colspan="3" style="padding:5px;">支持 <asp:Literal ID="Literal4" runat="server"></asp:Literal>格式。</td>
 </tr>
 </table>
 <div class="uploadbox">
 <span class="uploadbox_t">列表</span>
 <div id="divprogresscontainer"></div>
 <div id="divprogressGroup"></div> 
 <div id="piclist">
 <ul> 
 
 </ul> 
 </div> 
 </div>
 <br /><br />
 <input type="hidden" name="tb_imgurls" id="tb_imgurls" value=""/><br />
 <input type="hidden" name="piclists" id="piclists" value=""/>
 <div style="margin-left:300px;clear:both;">
 <table>
 <tr>
<!-- 此处是用于我项目Thickbox应用 可忽略-->
 <td><div class="submit"><input type="button" value="确定" onclick="confirmupload()"/></div></td>
 <td><div class="submit"><input type="button" value="取消" onclick="parent.TB_remove();" /></div> </td>
 </tr>
<!-- end -->
 </table>
 
 
 </div>
 </form>
 
</body>
</html>

swfupload.aspx.cs 文件源码

using System;
using System.Collections.Generic;
 
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
 
namespace yuyue.upload
{
 public partial class swfupload : System.Web.UI.Page
 {
 protected void Page_Load(object sender, EventArgs e)
 {
 if (!IsPostBack)
 { 
 //构造 swfupload.swf 所需js文件 
 Literal1.Text += "<script type=\"text/javascript\">\n";
 Literal1.Text += " var swfu;\n";
 
 Literal1.Text += " window.onload = function () {\n";
 Literal1.Text += " var settings = {\n";
 Literal1.Text += " flash_url: \"/statics/js/swfupload/swfupload.swf\",\n";
 Literal1.Text += " upload_url: \"upload.ashx\",\n";
 if (Request.QueryString["file_size_limit"] != null)
 {
 Literal1.Text += " file_size_limit: \"" + Request.QueryString["file_size_limit"] + "\",\n";//文件大小限制
 Literal3.Text = Request.QueryString["file_size_limit"];
 }
 else
 {
 Literal1.Text += " file_size_limit: \"2 MB\",\n";
 Literal3.Text = "2 MB";//文件大小限制
 }
 
 if (Request.QueryString["file_types"] != null)
 {
 Literal1.Text += " file_types: \"" + Request.QueryString["file_types"] + "\",\n";
 Literal4.Text = Request.QueryString["file_types"];
 }
 else
 {
 Literal1.Text += " file_types: \"*.*\",\n";
 Literal4.Text = "*.*";
 }
 
 if (Request.QueryString["file_types_description"] != null)
 {
 Literal1.Text += " file_types_description: \"" + Request.QueryString["file_types_description"] + "\",\n";
 }
 else
 {
 Literal1.Text += " file_types_description: \"All Files\",\n";
 }
 
 if (Request.QueryString["file_upload_limit"] != null)
 {
 Literal1.Text += " file_upload_limit: " + Request.QueryString["file_upload_limit"] + ",\n";
 Literal2.Text = Request.QueryString["file_upload_limit"];
 Literal2.Text = "50";
 }
 else
 {
 Literal1.Text += " file_upload_limit: 50,\n";
 } 
 
 Literal1.Text += " file_queue_limit: 0,\n";
 Literal1.Text += " autoremove: true, //是否自动移除完成上传的记录\n";
 Literal1.Text += " custom_settings: {\n";
 
 Literal1.Text += " progressTarget: \"divprogresscontainer\",\n";
 Literal1.Text += " progressGroupTarget: \"divprogressGroup\",\n";
 
 
 //progress object
 Literal1.Text += " container_css: \"progressobj\",\n";
 Literal1.Text += " icoNormal_css: \"IcoNormal\",\n";
 Literal1.Text += " icoWaiting_css: \"IcoWaiting\",\n";
 Literal1.Text += " icoUpload_css: \"IcoUpload\",\n";
 Literal1.Text += " fname_css: \"fle ftt\",";
 Literal1.Text += " state_div_css: \"statebarSmallDiv\",\n";
 Literal1.Text += " vstate_bar_css: \"statebar\",\n";
 Literal1.Text += " percent_css: \"ftt\",\n";
 Literal1.Text += " href_delete_css: \"ftt\",\n";
 
 
 //sum object
 /*
 页面中不应出现以"cnt_"开头声明的元素
 */
 Literal1.Text += " s_cnt_progress: \"cnt_progress\",\n";
 Literal1.Text += " s_cnt_span_text: \"fle\",";
 Literal1.Text += " s_cnt_progress_statebar: \"cnt_progress_statebar\",\n";
 Literal1.Text += " s_cnt_progress_percent: \"cnt_progress_percent\",\n";
 Literal1.Text += " s_cnt_progress_uploaded:\"cnt_progress_uploaded\",\n";
 Literal1.Text += " s_cnt_progress_size: \"cnt_progress_size\"\n";
 Literal1.Text += " },\n";
 Literal1.Text += " debug: false,\n";
 // Button settings
 Literal1.Text += " button_image_url: \"/statics/js/swfupload/images/swfBnt_select.png\",\n";
 Literal1.Text += " button_width: \"75\",\n";
 Literal1.Text += " button_height: \"28\",\n";
 Literal1.Text += " button_placeholder_id: \"spanButtonPlaceHolder\",\n";
 //button_cursor="HAND",
 //button_text: '',
 //button_text_style: ".theFont { font-size: 12;color:#0068B7;}", 
 //button_text_left_padding: 12,
 //button_text_top_padding: 3,
 
 
 
 // The event handler functions are defined in handlers.js
 Literal1.Text += " file_queued_handler: fileQueued,\n";
 Literal1.Text += " file_queue_error_handler: fileQueueError,\n";
 Literal1.Text += " upload_start_handler: uploadStart,\n";
 Literal1.Text += " upload_progress_handler: uploadProgress,\n";
 Literal1.Text += " upload_error_handler: uploadError,\n";
 Literal1.Text += " upload_success_handler: uploadSuccess,\n";
 Literal1.Text += " upload_complete_handler: uploadComplete\n";
 //file_dialog_complete_handler: fileDialogComplete
 
 Literal1.Text += " };\n";
 Literal1.Text += " swfu = new SWFUpload(settings);\n";
 Literal1.Text += "};\n";
 Literal1.Text += "</script>\n";
 }
 }
 }
}

下载源码

asp.net(c#)+flash(swfupload) 多图片批量上传源码下载   

总结

swfupload 多文件上传可用于多种类型文件上传,这里只演示了图片,你可以自己扩展。

同理,swfupload是不依赖于某个平台或者语言的,同样可用于PHP,Java,Asp.net等多种语言,只要您弄清楚原理就可以随意扩展,如有什么不明白的可给我留言。