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


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

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

    使用工具 vs 2010。

    演示效果图

    asp.net+swfupload 多图片批量上传(附源码下载) - 第1张  | 码农小兵asp.net+swfupload 多图片批量上传(附源码下载) - 第2张  | 码农小兵

    asp.net+swfupload 多图片批量上传(附源码下载) - 第3张  | 码农小兵

    第一步 新建一个web项目

    asp.net+swfupload 多图片批量上传(附源码下载) - 第4张  | 码农小兵

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

    asp.net+swfupload 多图片批量上传(附源码下载) - 第5张  | 码农小兵

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

    asp.net+swfupload 多图片批量上传(附源码下载) - 第6张  | 码农小兵

    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 多图片批量上传(附源码下载) - 第7张  | 码农小兵

    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">
    ";
     Literal1.Text += " var swfu;
    ";
     
     Literal1.Text += " window.onload = function () {
    ";
     Literal1.Text += " var settings = {
    ";
     Literal1.Text += " flash_url: "/statics/js/swfupload/swfupload.swf",
    ";
     Literal1.Text += " upload_url: "upload.ashx",
    ";
     if (Request.QueryString["file_size_limit"] != null)
     {
     Literal1.Text += " file_size_limit: "" + Request.QueryString["file_size_limit"] + "",
    ";//文件大小限制
     Literal3.Text = Request.QueryString["file_size_limit"];
     }
     else
     {
     Literal1.Text += " file_size_limit: "2 MB",
    ";
     Literal3.Text = "2 MB";//文件大小限制
     }
     
     if (Request.QueryString["file_types"] != null)
     {
     Literal1.Text += " file_types: "" + Request.QueryString["file_types"] + "",
    ";
     Literal4.Text = Request.QueryString["file_types"];
     }
     else
     {
     Literal1.Text += " file_types: "*.*",
    ";
     Literal4.Text = "*.*";
     }
     
     if (Request.QueryString["file_types_description"] != null)
     {
     Literal1.Text += " file_types_description: "" + Request.QueryString["file_types_description"] + "",
    ";
     }
     else
     {
     Literal1.Text += " file_types_description: "All Files",
    ";
     }
     
     if (Request.QueryString["file_upload_limit"] != null)
     {
     Literal1.Text += " file_upload_limit: " + Request.QueryString["file_upload_limit"] + ",
    ";
     Literal2.Text = Request.QueryString["file_upload_limit"];
     Literal2.Text = "50";
     }
     else
     {
     Literal1.Text += " file_upload_limit: 50,
    ";
     } 
     
     Literal1.Text += " file_queue_limit: 0,
    ";
     Literal1.Text += " autoremove: true, //是否自动移除完成上传的记录
    ";
     Literal1.Text += " custom_settings: {
    ";
     
     Literal1.Text += " progressTarget: "divprogresscontainer",
    ";
     Literal1.Text += " progressGroupTarget: "divprogressGroup",
    ";
     
     
     //progress object
     Literal1.Text += " container_css: "progressobj",
    ";
     Literal1.Text += " icoNormal_css: "IcoNormal",
    ";
     Literal1.Text += " icoWaiting_css: "IcoWaiting",
    ";
     Literal1.Text += " icoUpload_css: "IcoUpload",
    ";
     Literal1.Text += " fname_css: "fle ftt",";
     Literal1.Text += " state_div_css: "statebarSmallDiv",
    ";
     Literal1.Text += " vstate_bar_css: "statebar",
    ";
     Literal1.Text += " percent_css: "ftt",
    ";
     Literal1.Text += " href_delete_css: "ftt",
    ";
     
     
     //sum object
     /*
     页面中不应出现以"cnt_"开头声明的元素
     */
     Literal1.Text += " s_cnt_progress: "cnt_progress",
    ";
     Literal1.Text += " s_cnt_span_text: "fle",";
     Literal1.Text += " s_cnt_progress_statebar: "cnt_progress_statebar",
    ";
     Literal1.Text += " s_cnt_progress_percent: "cnt_progress_percent",
    ";
     Literal1.Text += " s_cnt_progress_uploaded:"cnt_progress_uploaded",
    ";
     Literal1.Text += " s_cnt_progress_size: "cnt_progress_size"
    ";
     Literal1.Text += " },
    ";
     Literal1.Text += " debug: false,
    ";
     // Button settings
     Literal1.Text += " button_image_url: "/statics/js/swfupload/images/swfBnt_select.png",
    ";
     Literal1.Text += " button_ "75",
    ";
     Literal1.Text += " button_height: "28",
    ";
     Literal1.Text += " button_placeholder_id: "spanButtonPlaceHolder",
    ";
     //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,
    ";
     Literal1.Text += " file_queue_error_handler: fileQueueError,
    ";
     Literal1.Text += " upload_start_handler: uploadStart,
    ";
     Literal1.Text += " upload_progress_handler: uploadProgress,
    ";
     Literal1.Text += " upload_error_handler: uploadError,
    ";
     Literal1.Text += " upload_success_handler: uploadSuccess,
    ";
     Literal1.Text += " upload_complete_handler: uploadComplete
    ";
     //file_dialog_complete_handler: fileDialogComplete
     
     Literal1.Text += " };
    ";
     Literal1.Text += " swfu = new SWFUpload(settings);
    ";
     Literal1.Text += "};
    ";
     Literal1.Text += "</script>
    ";
     }
     }
     }
    }

    下载源码

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

    总结

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

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

  • 相关阅读:
    2019年3月博客汇总
    赞美郭老师
    多项式初步
    Linux 下安装配置 JDK
    Python搜索目录下指定的文件,并返回绝对路径(包括子目录)
    Python所有的错误都是从BaseException类派生的,常见的错误类型和继承关系
    Python地址簿
    PHP正确的使用复数
    seq
    date
  • 原文地址:https://www.cnblogs.com/manongxiaobing/p/4694263.html
Copyright © 2020-2023  润新知