1. 程式人生 > >c#多檔案上傳簡單實現

c#多檔案上傳簡單實現

實現效果:前端實現自定義多檔案上傳。

此處需要注意的是form標籤裡面新增屬性(enctype="multipart/form-data")因為比較簡單廢話不說,直接上程式碼。

前端頁面:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="uploadfiles.aspx.cs" Inherits="Web.uploadfiles" %>

<!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 src="Scripts/jquery.js" type="text/javascript"></script>
    <script type="text/javascript">
        function Add() {
            $("#btnImg").before("<br /><input type=\"file\" name=\"imgUp\" /> ");
        }
    </script>
</head>
<body>
    <form id="form1" runat="server" enctype="multipart/form-data">
    <div id="imgDiv">
        <input type="file" name="imgUp" />
        <input id="btnImg" type="button" value="新增圖片" onclick="Add();" />
    </div>
    <asp:Button ID="Button1" runat="server" Text="上傳圖片" OnClick="Button1_Click" />
    </form>
</body>
</html>

後端cs程式碼:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Web
{
    public partial class uploadfiles : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
 
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            HttpFileCollection collection = Request.Files;
            for (int i = 0; i < collection.Count; i++)
            {
                HttpPostedFile postFile = collection[i];
                string fileName = postFile.FileName;
                fileName = fileName.Substring(fileName.LastIndexOf('\\') + 1);
                postFile.SaveAs(Server.MapPath("~/files/" + fileName));
            }
        }
    }
}