ASP.NET(C#)實現一次性上傳多張圖片(多個文件)

在做asp.net的Web開發的時候,我們經常會遇到一次性上傳多個文件的需求。通常我們的解決方法是固定放多個上傳文件框,這樣的解決辦法顯然是不合理的,因爲一次上傳多個,就意味着數量不確定。因此我們就要讓這些文件上傳框動態添加,下面我以我做的一個圖庫管理中的上傳圖片的功能爲例

先看效果:
打開的初始界面:


默認是上傳一個圖片,但當我們點“增加圖片”按鈕時可以實現選擇多個圖片及其描述同時上傳,本功能限制一次最多隻能上傳8張,且每張圖片大小不超過1M,這個大家可根據實際情況更改!
如圖:

下面來看實現過程:

第一步,使用javascript代碼實現動態添加文件上傳框和描述文本框,關鍵代碼如下:

<script type="text/javascript">
        
var i=1
        
function addFile()
        
{
     
         
if (i<8)
            
{var str = '<BR> <input type="file" name="File" runat="server" style="width: 300px"/>描述:<input name="text" type="text" style="width: 150px" maxlength="20" />'
            document.getElementById(
'MyFile').insertAdjacentHTML("beforeEnd",str)
        
            }

        
else
            
{
                alert(
"您一次最多隻能上傳8張圖片!")
            }

            i
++
        }

        
</script>
HTML調用代碼爲:
<id="MyFile"><INPUT onclick="addFile()" type="button" value="增加圖片(Add)"><br />
                                    
<input type="file" name="File" runat="server" style="width: 300px"/>
                                    描述:
<input name="text" type="text" style="width: 150px" maxlength="20" />


第二步:服務器端代碼實現
就上傳單個文件或圖片來說,使最普通不 過的了,但是對於這樣的一次性上傳多個文件以及它們相應的描述的問題,就要費點周折

    首先,通過System.Web.HttpContext.Current.Request.Files方法獲取客戶端的文件集合,然後通過Request.Form方法獲得描述文本框集合,最後利用一個循環將文件上傳,並將相應的信息保存到數據庫
關鍵代碼如下:

System.Web.HttpFileCollection files = System.Web.HttpContext.Current.Request.Files;
        
string[] rd = Request.Form[1].Split(',');//獲得圖片描述的文本框字符串數組,爲對應的圖片的描述
        string albumid=ddlAlbum.SelectedValue.Trim();
        
int ifile;
        
for (ifile = 0; ifile < files.Count; ifile++)
        
{
            
if (files[ifile].FileName.Length > 0)
            
{
                      ..........................  
//上傳單個文件並保存相關信息
             }

         }

最後給出上述功能的全部代碼:

HTML代碼:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="UploadImg.aspx.cs" Inherits="NetAdmin_APicture_UploadImg" %>

<!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>
        
<script type="text/javascript">
        
var i=1
        
function addFile()
        
{
     
         
if (i<8)
            
{var str = '<BR> <input type="file" name="File" runat="server" style="width: 300px"/>描述:<input name="text" type="text" style="width: 150px" maxlength="20" />'
            document.getElementById(
'MyFile').insertAdjacentHTML("beforeEnd",str)
        
            }

        
else
            
{
                alert(
"您一次最多隻能上傳8張圖片!")
            }

            i
++
        }

        
</script>
    
<link href="../../NetAdmin/Site.Css" rel="stylesheet" type="text/css" />
</head>
<body style="background-image: url(../images/bg.jpg); text-align: center">
    
<form id="form1" runat="server">
    
<div>
        
<table id="Table1" align="center" border="0" cellpadding="1" cellspacing="1" class="table"
            style
="height: 58px" width="620">
            
<tr>
                
<td align="center" background="../images/topbg1.jpg">
                    
<font color="#0000ff" face="宋體" size="3"><strong>上傳圖片</strong></font></td>
            
</tr>
            
<tr>
                
<td align="center">
                    
&nbsp;</td>
            
</tr>
            
<tr>
                
<td align="center">
                    
<asp:Panel ID="Panel5" runat="server" Width="608px">
                        
&nbsp; &nbsp;<table width="100%">
                            
<tr>
                                
<td align="right" style="width: 100px">
                                
</td>
                                
<td align="left">
                                    說明:點增加圖片按鈕可一次上傳多張圖片,可爲每張圖片寫上一句不超過20個字的描述。單張圖片大小不大於1024k
</td>
                            
</tr>
                            
<tr>
                                
<td align="right" style="width: 100px">
                                    請選擇圖片:
<br />
                                
</td>
                                
<td align="left"><id="MyFile"><INPUT onclick="addFile()" type="button" value="增加圖片(Add)"><br />
                                    
<input type="file" name="File" runat="server" style="width: 300px"/>
                                    描述:
<input name="text" type="text" style="width: 150px" maxlength="20" />
                                
</td>
                            
</tr>
                            
<tr>
                                
<td align="right" style="width: 100px">
                                    上傳到的圖庫:
</td>
                                
<td align="left">
                                    
<asp:DropDownList ID="ddlAlbum" runat="server" DataSourceID="SqlDataSource1"
                                        DataTextField
="AlbumName" DataValueField="AlbumID">
                                    
</asp:DropDownList><asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:WebJakeCS %>"
                                        SelectCommand
="SELECT [AlbumID], [AlbumName] FROM [WB_Album] ORDER BY [AlbumID] DESC">
                                    
</asp:SqlDataSource>
                                
</td>
                            
</tr>
                            
<tr>
                                
<td align="right" style="width: 100px">
                                
</td>
                                
<td align="left">
                                    
<asp:Button ID="btnUpload" runat="server" Text="開始上傳" OnClick="btnUpload_Click" />
                                    
</td>
                            
</tr>
                            
<tr>
                                
<td align="right" style="width: 100px">
                                
</td>
                                
<td align="left">
                                    
<asp:Label ID="lblMessage" runat="server" Font-Bold="True" ForeColor="Red"></asp:Label></td>
                            
</tr>
                        
</table>
                    
</asp:Panel>
                    
&nbsp;
                
</td>
            
</tr>
            
<tr>
                
<td align="center">
                    
<font face="宋體"></font><font face="宋體">&nbsp;</font>
                
</td>
            
</tr>
            
<tr>
                
<td align="center">
                    
<font face="宋體"></font>
                
</td>
            
</tr>
        
</table>
    
    
</div>
    
</form>
</body>
</html>

後臺代碼:
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 NetAdmin_APicture_UploadImg : System.Web.UI.Page
{
    
protected void Page_Load(object sender, EventArgs e)
    
{

    }

   
    
protected void btnUpload_Click(object sender, EventArgs e)
    
{
        lblMessage.Text 
= "";
        lblMessage.Visible 
= false;
        System.Web.HttpFileCollection files 
= System.Web.HttpContext.Current.Request.Files;
        System.Text.StringBuilder strmsg 
= new System.Text.StringBuilder("");
        
string[] rd = Request.Form[1].Split(',');//獲得圖片描述的文本框字符串數組,爲對應的圖片的描述
        string albumid=ddlAlbum.SelectedValue.Trim();
        
int ifile;
        
for (ifile = 0; ifile < files.Count; ifile++)
        
{
            
if (files[ifile].FileName.Length > 0)
            
{
                System.Web.HttpPostedFile postedfile 
= files[ifile];
                
if (postedfile.ContentLength / 1024 > 1024)//單個文件不能大於1024k
                {
                    strmsg.Append(Path.GetFileName(postedfile.FileName) 
+ "---不能大於1024k<br>");
                    
break;
                }

                
string fex = Path.GetExtension(postedfile.FileName);
                
if (fex != ".jpg" && fex != ".JPG" && fex != ".gif" && fex != ".GIF")
                
{
                    strmsg.Append(Path.GetFileName(postedfile.FileName) 
+ "---圖片格式不對,只能是jpg或gif<br>");
                    
break;
                }

            }

        }

        
if (strmsg.Length <= 0)//說明圖片大小和格式都沒問題
        {
            
//以下爲創建圖庫目錄
            string dirname = "pic00" + ddlAlbum.SelectedValue.Trim();
            
string dirpath = Server.MapPath("../../PicBase");
            dirpath 
= dirpath + "/" + dirname;
            
if (Directory.Exists(dirpath) == false)
            
{
                Directory.CreateDirectory(dirpath);
            }

            Random ro 
= new Random();
            
int name = 1;
            
for (int i = 0; i < files.Count; i++)
            
{
                System.Web.HttpPostedFile myFile 
= files[i];
                
string FileName = "";
                
string FileExtention = "";
                
string PicPath = "";
                FileName 
= System.IO.Path.GetFileName(myFile.FileName);  
                
string stro=ro.Next(100,100000000).ToString()+name.ToString();//產生一個隨機數用於新命名的圖片
                string NewName =DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString()+DateTime.Now.Millisecond.ToString()+stro;
                
if (FileName.Length > 0)//有文件才執行上傳操作再保存到數據庫
                {
                    FileExtention 
= System.IO.Path.GetExtension(myFile.FileName);

                    
string ppath = dirpath + "/" + NewName + FileExtention;
                    myFile.SaveAs(ppath);
                    
string FJname = FileName;
                    PicPath 
= "PicBase" + "/" + dirname + "/" + NewName + FileExtention;
                   
                }

                AddPicture(PicPath, rd[i], albumid);
//將圖片信息保存到數據庫
                if (name == 1)//如果爲每次更新的第一張圖片,則將它更新爲象冊的封面
                {
                    upFirstimg(albumid, PicPath);
                }

                name 
= name + 1;//用來重命名規則的變量
                
            }

        }

        
else
        
{
            lblMessage.Text 
= strmsg.ToString();
            lblMessage.Visible 
= true;
        }

    }

    
private void AddPicture(string imgpath,string imgnote,string albumid)
    
{
        
string sql = "insert WB_AlbumImges(ImgPath,ImgNote,AlbumID) values('"+imgpath+"','"+imgnote+"','"+albumid+"')";
        DB mydb 
= new DB();
        mydb.RunProc(sql);
    }

    
private void upFirstimg(string albumid,string firstimg)
    
{
        
string sql = "update WB_Album set FirstImg='"+firstimg+"' where AlbumID="+albumid;
        DB mydb 
= new DB();
        mydb.RunProc(sql);
    }

}

發佈了45 篇原創文章 · 獲贊 7 · 訪問量 14萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章