Javascript與asp.net多檔案無重新整理上傳 – Huacn的日誌 – 部落格園

來源:互聯網
上載者:User
文章目錄
  • Javascript與asp.net 實現Ajax多檔案無重新整理上傳

 

Javascript與asp.net多檔案無重新整理上傳

Javascript與asp.net 實現Ajax多檔案無重新整理上傳

這幾天在等著上班,閑來無事,就寫了一個無重新整理的上傳功能,這個上傳只是實現局部重新整理,我已經把方法都整理好,可以隨意添加多個上傳控制項,只要調用一個方法就可以了,為了便於閱讀我沒有把JS獨立出來,以後真正用到項目上的時候再提出來,我在每個方法上面都寫了注視,具體可以看代碼部分,現在一直在用JQuery,它提供的方法太好用的,剩了很多事。
此方法主要是通過iFrame調用上傳頁的控制項來實現的,具體請看下面的代碼。

無重新整理上傳主要的HTML代碼(upload.html):

<!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>
<title>AjaxUpload</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="scripts/jquery.js"></script>
<script type="text/javascript" src="scripts/interface.js"></script>
<style type="text/css" media="all">
*{
    margin:0;
    padding:0;
}
img{border:none;}
ul{
    list-style-type:none;
}
ul li{
    padding:2px 4px;
}
body{
    font-family: 宋體, 黑體,verdana, Arial;
    font-size:12px;
    color:#333;
    background:#DDDDDD;
    margin:30px;
    padding:0;
}
.box{
    border:1px solid #CCC;
    background:#FFF;
    padding:8px;
    margin:5px;
    clear:both;
}
.title {
    background:#F0F0F0;padding:5px;
    font-weight:bold;
}
.tooltip{
    background:#F0F0F0;
    border-color:#bbb;
}
.tooltip h1 {
    color:#A8DF00;
    font-family: 微軟雅黑,黑體,宋體,verdana, Arial;
}
.titlebutton{
    float:right;
}
.uploading{
    background:#FFF;
    color:#444;
    text-align:left;
    width:500px;
    padding:4px;
}
.image{
    border:1px solid #ddd;
    margin:2px;
    padding:1px;
    display:inline;
    width:300px;
}
.uploadcontrol {
    margin:4px 0;
    border-bottom:1px solid #F0F0F0;
}
</style>
<script type="text/javascript">
     $(document).ready(function(){         
for(var i=0;i<5;i++)
          {
             uploadcreate($("#uploadbox"),i);
          }
    });
var hideDiv = function(idName){
         $("#"+idName).fadeOut("fast");
     };
//是否顯示上傳後的圖片
var isshowpic = true; 
var uploadshowpic = function(el){
         isshowpic = !(isshowpic);
if(isshowpic)
         {
             el.html("圖片顯示關閉");
         }
else
         {
             el.html("圖片顯示開啟");
         }
     };
//載入中的GIF動畫
var loadingUrl = "images/ajax-loader.gif";
//選擇檔案後的事件,iframe裡面調用的
var uploading = function(imgsrc,itemid){
var el = $("#uploading"+itemid);
        $("#ifUpload"+itemid).fadeOut("fast");
        el.fadeIn("fast");
        el.html("<img src='"+loadingUrl+"' align='absmiddle' /> 上傳中");
return el;
    };
//重新上傳方法   
var uploadinit = function(itemid){
        currentItemID ++;
        $("#uploading"+itemid).fadeOut("fast",function(){
             $("#ifUpload"+itemid).fadeIn("fast");
             $("#panelViewPic"+itemid).fadeOut("fast");
        });
    };
//上傳時程式發生錯誤時,給提示,並返回上傳狀態
var uploaderror = function(itemid){
        alert("程式異常,"+itemid+"項上傳未成功。");
        uploadinit();
    };
//上傳成功後的處理
var uploadsuccess = function(newpath,itemid){
        $("#uploading"+itemid).html("檔案上傳成功. <a href='javascript:void(0);' onclick='uploadinit("+itemid+");'>[重新上傳]</a>");
if(isshowpic)
        {
            $("#panelViewPic"+itemid).html("<a href='"+newpath+"' title='點擊查看大圖' target='_blank'><img src='"+newpath+"' alt='' style='width:300px;' /></a>");       
            $("#panelViewPic"+itemid).fadeIn("fast");
        }
    };
var currentItemID = 0;  //用於存放共有多少個上傳控制項了
//建立一個上傳控制項
var uploadcreate = function(el,itemid){
        currentItemID ++;
if(itemid == null)
        {
            itemid = currentItemID;
        } 
var strContent = "<div class='uploadcontrol'><iframe src=\"upload.aspx?id="+itemid+"\" id=\"ifUpload"+itemid+"\" frameborder=\"no\" scrolling=\"no\" style=\"width:400px; height:28px;\"></iframe>";
        strContent += "<div class=\"uploading\" id=\"uploading"+itemid+"\" style=\"display:none;\" ></div>";
        strContent += "<div class=\"image\" id=\"panelViewPic"+itemid+"\" style=\"display:none;\"></div></div>";
        el.append(strContent);
    };
</script>
</head>
<body>
<div id="tipbox" class="box tooltip">
<a href="#" onclick="hideDiv('tipbox');">[關閉]</a>
<div class="content">
<h1>AjaxUpload - 多檔案無重新整理上傳原始碼 v1.0</h1>
<p>作者:李華順 <a href="http://huacn.cnblogs.com" target="_blank">http://huacn.cnblogs.com</a></p>
</div>
</div>
<div id="toolbox" class="tooltip box">
<a href="#" onclick="uploadcreate($('#uploadbox'));">添加一個新上傳控制項</a> <a href="#" onclick="uploadshowpic($(this));">圖片顯示關閉</a>
</div>
<div id="uploadbox" class="box">
</div>
</body>
</html>

上傳功能的頁面代碼(upload.aspx):

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="upload.aspx.cs" Inherits="upload" %>
<!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>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="scripts/jquery.js"></script>
<script type="text/javascript" src="scripts/interface.js"></script>
<style type="text/css">
        *{ margin:0; padding:0; }
</style>
<script type="text/javascript">
var uploadSelect = function(el){
            el.fadeOut("show");       
            parent.uploading(document.getElementById("<%=file1.ClientID %>").value,'<%=itemID %>');
            $("#<%=frmUpload.ClientID %>").submit();
        };
</script>
</head>
<body>
<form runat="server" id="frmUpload" method="post" enctype="multipart/form-data">
<input type="file" runat="server" id="file1" size="40" onchange="uploadSelect($(this));" />
</form>
</body>
</html>

上傳功能的服務端代碼(upload.aspx.cs)

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
public partial class upload : System.Web.UI.Page
{
string picPath = "";
string picServer = "/upload";
protected string itemID = "";
protected void Page_Load(object sender, EventArgs e)
    {
if (Request.QueryString["id"] != null)
        {
            itemID = Request.QueryString["id"];
        }
if (IsPostBack)
        {
            picPath = Server.MapPath("\\upload");
            doUpload();
        }
    }
protected void doUpload()
    {
try
        {
            HttpPostedFile file = file1.PostedFile;
string strNewPath = GetSaveFilePath() + GetExtension(file.FileName);
            file.SaveAs(picPath+strNewPath);
string urlPath = picServer + strNewPath;
            urlPath = urlPath.Replace("\\", "/");
            WriteJs("parent.uploadsuccess('" + urlPath + "','" + itemID + "'); ");
        }
catch (Exception ex)
        {
            WriteJs("parent.uploaderror();");           
        }
    }
private string GetExtension(string fileName)
    {
try
        {
int startPos = fileName.LastIndexOf(".");
string ext = fileName.Substring(startPos, fileName.Length - startPos);
return ext;
        }
catch (Exception ex)
        {
            WriteJs("parent.uploaderror('" + itemID + "');");
return string.Empty;
        }
    }
private string GetSaveFilePath()
    {
try
        {
            DateTime dateTime = DateTime.Now;
string yearStr = dateTime.Year.ToString(); ;
string monthStr = dateTime.Month.ToString();
string dayStr = dateTime.Day.ToString();
string hourStr = dateTime.Hour.ToString();
string minuteStr = dateTime.Minute.ToString();
string dir = dateTime.ToString(@"\\yyyyMMdd");
if (!Directory.Exists(picPath + dir))
            {
                Directory.CreateDirectory(picPath + dir);
            }
return dir + dateTime.ToString("\\\\yyyyMMddhhmmssffff");
        }
catch (Exception ex)
        {
            WriteJs("parent.uploaderror();");
return string.Empty;
        }
    }
protected void WriteJs(string jsContent)
    {       
this.Page.RegisterStartupScript("writejs","<script type='text/javascript'>"+ jsContent+"</script>");
    }
}

基本上就是這些,重點請看第一部份的代碼,主要是JS控制項顯示,還有一個重點是upload.aspx調用父級頁面的方法這些實現。
Javascript無重新整理上傳示範地址:http://www.wathon.com/opensource/js/ajaxuploadv1/upload.html
原始碼:http://www.wathon.com/opensource/js/ajaxuploadv1/ajaxupload_src.zip
無重新整理上傳在編輯框中的應用示範:http://files.cnblogs.com/huacn/ajaxupload_example.zip

Javascript與asp.net多檔案無重新整理上傳 - Huacn的日誌 - 部落格園

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.