fileupload控件只上传1个文件

时间:2015-02-25 14:02:16

标签: c# asp.net sql-server-2012

我正在尝试让上传控件上传多个文件,但它只上传一个,我不知道为什么。此外,我想调用存储过程,当且仅当所有必需文件都已成功上传时。任何建议都会有所帮助,因为我不知所措。我确定它在我的foreach循环中做错了但我不确定究竟是什么。

我的标记:

<%@ Page Title="" Language="C#" MasterPageFile="~/Admin/AdminMaster.master" AutoEventWireup="true" CodeFile="addFont.aspx.cs" Inherits="Admin_addFont" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="Server"></asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="RightCol" runat="Server">    
<h1>Fonts</h1>    
<h2>Currently available fonts</h2>
<div><asp:Label ID="lblFontGrd" runat="server"></asp:Label>
    <asp:GridView ID="grdFonts" runat="server" CellPadding="4" ForeColor="#333333" GridLines="None" AutoGenerateColumns="False"
         OnPageIndexChanging="grdFonts_PageIndexChanging">
        <AlternatingRowStyle BackColor="White" ForeColor="#284775"></AlternatingRowStyle>

        <Columns>
            <asp:TemplateField AccessibleHeaderText="ID" FooterText="ID" HeaderText="ID">
                <ItemTemplate>
                    <asp:Label ID="fontId" runat="server" Text='<%# Eval("FontId") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField AccessibleHeaderText="Font Name" FooterText="Font Name" HeaderText="Font Name">
                <ItemTemplate>
                    <asp:Label ID="lblfontName" runat="server" Text='<%# Eval("FontName") %>'></asp:Label>
                </ItemTemplate>
                <EditItemTemplate>
                    <asp:Label ID="lblfontNameEdit" runat="server" Text='<%# Eval("FontName") %>'></asp:Label>
                </EditItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField AccessibleHeaderText="Example" FooterText="Example" HeaderText="Example">
                <ItemTemplate>
                    <asp:Label id="lblfontExample" runat="server" Font-Size="Large" Font-Names='<%# BuildFont(Eval("FontFamily").ToString()) %>' ><h3>This is an example of the font</h3></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField AccessibleHeaderText="Discontinued?" HeaderText="Discontinued?" FooterText="Discontinued?">
                <ItemTemplate>
                    <asp:CheckBox ID="Discontinued" runat="server" Checked='<%# Eval("Discontinued") %>' Enabled="false" />
                </ItemTemplate>
                <EditItemTemplate>
                    <asp:CheckBox ID="Discontinued" runat="server" Checked='<%# Eval("Discontinued") %>' Enabled="true" />
                </EditItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Edit">
                <ItemTemplate>
                    <span onclick="return confirm('Are you sure you want to delete?')">
                        <asp:LinkButton ID="btnDelete" Text="Delete" runat="server" CommandName="Delete" />
                    </span>
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>

        <EditRowStyle BackColor="#999999"></EditRowStyle>

        <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White"></FooterStyle>

        <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White"></HeaderStyle>

        <PagerStyle HorizontalAlign="Center" BackColor="#284775" ForeColor="White"></PagerStyle>

        <RowStyle BackColor="#F7F6F3" ForeColor="#333333"></RowStyle>

        <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333"></SelectedRowStyle>

        <SortedAscendingCellStyle BackColor="#E9E7E2"></SortedAscendingCellStyle>

        <SortedAscendingHeaderStyle BackColor="#506C8C"></SortedAscendingHeaderStyle>

        <SortedDescendingCellStyle BackColor="#FFFDF8"></SortedDescendingCellStyle>

        <SortedDescendingHeaderStyle BackColor="#6F8DAE"></SortedDescendingHeaderStyle>
    </asp:GridView>
</div>
<div>

    <h2>Add a new font</h2>
    <asp:Label ID="lblUpload" runat="server" ForeColor="Red"></asp:Label>
    <p>In order to add a new font to the library please follow the steps laid out below:</p>
    <p><strong>Step 1:&nbsp;</strong>&nbsp;The first, and most important, thing to do is make sure you have the appropriate license to use your font for print and web.</p>
    <p><strong>Step 2:&nbsp;</strong>&nbsp;Next you need to convert your font file into multple formats to ensure browser compatability. 
        To do so please follow <a target="_blank" href="http://www.fontsquirrel.com/tools/webfont-generator">this</a> link. 
        Select OPTIMAL and upload your file. Unzip the files generated by the tool.</p>
    <p><strong>Step 3:&nbsp;</strong>&nbsp;Now you need open the file that ends with '.css', a simple text editor such as notepad will do just fine.</p>
    <p><strong>Step 4:&nbsp;</strong>&nbsp;Find the font-family property(see image below)</p><br />
    <asp:Image ID="imgFontCssEx" runat="server" ImageUrl="~/Images/fontCssImg.png" /><br />
    <p><strong>Step 5:&nbsp;</strong>&nbsp; Make sure you copy the font-family value exactly as shown in the css into the text box below, marked Font Name.</p>
    <asp:TextBox ID="txtFontFam" runat="server"></asp:TextBox>&nbsp;
    <asp:Label ID="lblFontFam" runat="server" Text="Font Family"></asp:Label>
    <br />
    <p><strong>Step 6:&nbsp;</strong>&nbsp;Enter a display name for your font.</p>
    <asp:TextBox ID="txtFontName" runat="server"></asp:TextBox>&nbsp;
    <asp:Label ID="lblFontName" runat="server" Text="Display Name" ></asp:Label>
    <br />
    <p><strong>Step 7:&nbsp;</strong>&nbsp;Now you need to upload the files specified below:</p><br />
    <asp:FileUpload ID="flupFonts" runat="server" AllowMultiple="true" />&nbsp;
    <asp:Label ID="lblCss" runat="server" AssociatedControlID="flupFonts" Text="Upload file with files ending: .css, .ttf, .svg, .eot, .woff, .woff2"></asp:Label>

    <p><strong>Finally:&nbsp</strong>&nbsp;Click the button below and the font will be made available.</p>
    <br />
    <asp:Button ID="btnUploadFont" runat="server" Text="Add Font" OnClick="btnUploadFont_Click" />
</div>

我的代码背后:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Drawing;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlTypes;
using System.Data.SqlClient;
using System.Web.Configuration;
using System.IO;
using System.Data;

public partial class Admin_addFont : System.Web.UI.Page
{
private string fontUploadDirectory;


private string connectionString =
  WebConfigurationManager.ConnectionStrings["bncConn"].ConnectionString;

protected void Page_Load(object sender, EventArgs e)
{
    // ensure files are uploaded to the right folder
    fontUploadDirectory = Server.MapPath(@"~\fonts\");

    if (!this.IsPostBack)
    {
        BindGrid();

    }

}

protected void BindGrid()
{

    // define ado.net objects
    SqlConnection con = new SqlConnection(connectionString);
    SqlCommand cmd = new SqlCommand("ProductDetails.bnc_Fonts", con);
    cmd.CommandType = CommandType.StoredProcedure;
    SqlDataAdapter adapter = new SqlDataAdapter(cmd);
    // define parameters
    cmd.Parameters.Add(new SqlParameter("@status", SqlDbType.VarChar, 50));
    cmd.Parameters["@status"].Value = "Display";

    // attempt to connect to db, read data, fill dataset and bind gridview. Catch exceptions and close the connection.
    try
    {
        con.Open();
        DataSet ds = new DataSet();
        adapter.Fill(ds, "Fonts");
        grdFonts.DataSource = ds;
        grdFonts.DataBind();
    }
    catch (Exception err)
    {
        lblFontGrd.Text = err.Message;
    }
    finally
    {
        con.Close();
    }
}

protected void grdFonts_PageIndexChanging(object sender, GridViewPageEventArgs e)
{

    grdFonts.PageIndex = e.NewPageIndex;

    BindGrid();

}
public static string[] BuildFont(string font)
{
    string[] array = new string[1];
    array[0] = font;
    return array;
}


protected void btnUploadFont_Click(object sender, EventArgs e)
{

    string[] validFileTypes = { "eot", "ttf", "svg", "woff", "woff2", "css" };

    bool isValidFile = false;

    // check files are being submitted
    if (flupFonts.HasFiles == false)
    {
        lblUpload.Text = "No files have been selected.";
    }
    else
    {
        HttpFileCollection fileCollection = Request.Files;
        if (fileCollection.Count == 6)
        {
            string serverFileName = Path.GetFileName(flupFonts.PostedFile.FileName);
            string ext = Path.GetExtension(serverFileName).ToLower();
            string fullUploadPath = Path.Combine(fontUploadDirectory, serverFileName);

            try { 
            foreach (HttpPostedFile uploadedFont in flupFonts.PostedFiles)
            {                                           
                for (int i = 0; i < validFileTypes.Length; i++)
                {


                    if (ext == "." + validFileTypes[i])
                    {
                        isValidFile = true;



                        if (!File.Exists(fullUploadPath)) 
                        {
                            try
                            {
                                flupFonts.PostedFile.SaveAs(fullUploadPath);                                    
                                break;
                            }
                            catch (Exception err)
                            {
                                lblUpload.Text = err.Message;
                            }

                        }


                    }

                }
                if (!isValidFile)
                {
                    lblUpload.Text += "Invalid File. Please upload a File with extension " + string.Join(",", validFileTypes);
                }

            }

            fontDbInfo();
            BindGrid();
            }
            catch (Exception err)
            {
                lblUpload.Text = "Error: " + err.Message;
            }
        }
        else
        {
            if (fileCollection.Count < 6)
            {
                lblUpload.Text = "Please make sure you select all required files.";
            }
            if (fileCollection.Count > 6)
            {
                lblUpload.Text = "You have selected too many files. Please only add the required files.";
            }
        }

    }
}

protected void fontDbInfo()
{
    // define ado.net objects
    SqlConnection con = new SqlConnection(connectionString);
    SqlCommand cmd = new SqlCommand("ProductDetails.bnc_Fonts", con);
    cmd.CommandType = CommandType.StoredProcedure;
    SqlDataAdapter adapter = new SqlDataAdapter(cmd);
    // define sp parameters
    cmd.Parameters.Add(new SqlParameter("@Status", SqlDbType.VarChar, 50));
    cmd.Parameters["@Status"].Value = "Add";
    cmd.Parameters.Add(new SqlParameter("@FontName", SqlDbType.VarChar, 50));
    cmd.Parameters["@FontName"].Value = txtFontName.Text;
    cmd.Parameters.Add(new SqlParameter("@FontFamily", SqlDbType.VarChar, 50));
    cmd.Parameters["@FontFamily"].Value = txtFontFam.Text;
    cmd.Parameters.Add(new SqlParameter("@Discontinued", SqlDbType.Bit));
    cmd.Parameters["@Discontinued"].Value = 0;
    // try to open database, insert font info, catch errors and close the connection
    try
    {
        con.Open();
        cmd.ExecuteNonQuery();
        DataSet ds = new DataSet();
        adapter.Fill(ds, "Fonts");


    }
    catch (Exception err)
    {
        lblFontGrd.Text = "Error: " + err.Message;
    }
    finally
    {
        con.Close();
    }

}}

我的存储过程:

CREATE PROCEDURE [ProductDetails].[bnc_Fonts] 
-- Add the parameters for the stored procedure here
@Status varchar(50) = '', 
@FontId tinyint = '',
@FontName varchar(50) = '',
@FontFamily varchar(50) = '',
@Discontinued bit = ''
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;

if (@Status = 'Display')
begin
select FontId, FontName, FontFamily, Discontinued 
from ProductDetails.Fonts 
where Discontinued = 0
order by FontName asc   
end
if (@Status = 'FontFam')
begin
select FontFamily from ProductDetails.Fonts
where FontId = @FontId
end
if (@Status = 'Add')
begin
insert into ProductDetails.Fonts (FontName, FontFamily, Discontinued)
values (@FontName, @FontFamily, @Discontinued)
end
if (@Status = 'Delete')
begin
UPDATE ProductDetails.Fonts
SET Discontinued = @Discontinued
where FontId = @FontId
end
END

2 个答案:

答案 0 :(得分:0)

替换此循环:

        foreach (HttpPostedFile uploadedFont in flupFonts.PostedFiles)
        {
           ...   
        }     

有了这个:

        foreach(string key in flupFonts.Keys)
        {
           HttpPostedFile uploadedFont = flupFonts[key];
           ...
        }           

答案 1 :(得分:0)

我认为您尝试循环访问HttpPostedFile集合的方式会导致问题。尝试使用单独的方法检查文件有效性。我还建议你将这个问题分解成你可以测试的部分。例如,尝试使用类似这样的代码的简单测试页面。希望这会有所帮助。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Drawing;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlTypes;
using System.Data.SqlClient;
using System.Web.Configuration;
using System.IO;
using System.Data;

public partial class Test : System.Web.UI.Page
{
    private string fontUploadDirectory;

    protected void Page_Load(object sender, EventArgs e)
    {
        // ensure files are uploaded to the right folder
        fontUploadDirectory = Server.MapPath(@"~\fonts\");
    }

    protected void btnUploadFont_Click(object sender, EventArgs e)
    {
        string[] validFileTypes = { ".eot", ".ttf", ".svg", ".woff", ".woff2", ".css" };
        // check files are being submitted
        if (flupFonts.HasFiles == false)
        {
            lblUpload.Text = "No files have been selected.";
        }
        else
        {
            HttpFileCollection fileCollection = Request.Files;
            foreach (HttpPostedFile uploadedFont in flupFonts.PostedFiles)
            {
                string ext = System.IO.Path.GetExtension(uploadedFont.FileName);
                if (isValid(uploadedFont, validFileTypes, ext))
                {
                    uploadedFont.SaveAs(fontUploadDirectory + "\\" + System.IO.Path.GetFileName(uploadedFont.FileName));
                }
            }
        }
    }

    private bool isValid(HttpPostedFile file, string[] extAry, string ext)
    {
        bool isValid = false;
        for (int i = 0; i < extAry.Length; i++)
        {
            if (ext.ToLowerInvariant().IndexOf(extAry[i]) > -1)
                isValid = true;
        }
        return isValid;
    }
}