usercontrol页面中的fileupload控件

时间:2015-03-02 10:38:47

标签: asp.net vb.net file-upload

我正在尝试使用用户控制页面内的文件上传控件将文件上传到数据库。上传文件时,我收到一个错误,即控件中没有选择文件。

我在网上搜索了解决方案,我发现我需要为处理上传代码的按钮添加一个触发器。我还读到我需要添加Page.Form.Attributes.Add("enctype", "multipart/form-data")。在我的情况下似乎没有工作。

aspx文件:

<%@ Page Title="" Language="VB" MasterPageFile="~/MasterPage.master" CodeFile="Sessions.aspx.vb" Inherits="Sessions" %>
<%@ Register Src="~/Controls/SessionCtl.ascx" TagName="SessionCtl" TagPrefix="uc2" %>
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %>

 <asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
    <asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
        <ContentTemplate>
            <asp:Panel runat="server" ID="pnlAddUpdateSession" Visible="false">
                <div style="width: 900px; margin-left: auto; margin-right: auto; margin-top: 20px;">
                    <uc2:SessionCtl runat="server" ID="sessionCtl" />
                </div>
            </asp:Panel>
        </ContentTemplate>
        <Triggers>
            <asp:PostBackTrigger ControlID="btnAddSession" />
        </Triggers>
    </asp:UpdatePanel>
</asp:Content>

ascx文件:

<asp:Panel ID="panelAddUpdate" runat="server" GroupingText="Add session" Width="95%" CssClass="PanelADD">
    <div id="pnlFileUploadArea" style="align-content: center" class="gvProject">
        <asp:Label ID="label12" Text="Add Log:" runat="server"></asp:Label>
        <asp:RadioButtonList ID="RadioButtonList1" runat="server" RepeatDirection="Horizontal" RepeatLayout="Flow" AutoPostBack="True">
            <asp:ListItem Text="New" Value="0" Selected="True"></asp:ListItem>
            <asp:ListItem Text="Use Previous" Value="1"></asp:ListItem>
        </asp:RadioButtonList>
        <br />
        <div id="fileUploadContainer" runat="server">
            <div id="fileUploadControl">
                <asp:FileUpload ID="fuSelectedFile" runat="server"size="60"/>
            </div>
        </div>
        <br />
        <br />
    </div>
    <div style="padding: 5px 5px 5px 25px">
        <asp:Button ID="btnAddSession" runat="server" Text="Add" SkinID="fancybutton" />
        <asp:Button ID="btnCancelAddSession" runat="server" Text="Cancel" SkinID="fancybutton" />
    </div>
</asp:Panel>

ascx.vb文件:

    Protected Sub btnAddSession_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnAddSession.Click
    If (String.IsNullOrEmpty(validationMessage)) Then
    'validationMessage is a var I use to check if other fields are filled correctly
        If (RadioButtonList1.Items.FindByText("New").Selected = True) Then
            If Not (fuSelectedFile.HasFile) Then
                'upload files
            Else
                validationMessage = "No file selected!"
            End If
        End If
    End If
End Sub

aspx.vb文件:

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

    Page.Form.Attributes.Add("enctype", "multipart/form-data")

End Sub

2 个答案:

答案 0 :(得分:1)

您可以尝试

ascx文件

<asp:FileUpload ID="FileUpload1" runat="server" />

<asp:Button ID="btnUpload" runat="server" Text="Upload"

OnClick="btnUpload_Click" />

<br />

<asp:Label ID="lblMessage" runat="server" Text=""

Font-Names = "Arial"></asp:Label>

<强> ascx.cs

按钮上传活动

protected void btnUpload_Click(object sender, EventArgs e)

{

    // Read the file and convert it to Byte Array

    string filePath = FileUpload1.PostedFile.FileName;  

    string filename = Path.GetFileName(filePath);

    string ext = Path.GetExtension(filename);

    string contenttype = String.Empty;



    //Set the contenttype based on File Extension

    switch(ext)

    {

        case ".doc":

            contenttype = "application/vnd.ms-word";

            break;

        case ".docx":

            contenttype = "application/vnd.ms-word";

            break;

        case ".xls":

            contenttype = "application/vnd.ms-excel";

            break;

        case ".xlsx":

            contenttype = "application/vnd.ms-excel";

            break;

        case ".jpg":

            contenttype = "image/jpg";

            break;

        case ".png":

            contenttype = "image/png";

            break;

        case ".gif":

            contenttype = "image/gif";

            break;

        case ".pdf":

            contenttype = "application/pdf";

            break;

    }

    if (contenttype != String.Empty)

    {



        Stream fs = FileUpload1.PostedFile.InputStream;

        BinaryReader br = new BinaryReader(fs);

        Byte[] bytes = br.ReadBytes((Int32)fs.Length);



        //insert the file into database

        string strQuery = "insert into tblFiles(Name, ContentType, Data)" +

           " values (@Name, @ContentType, @Data)";

        SqlCommand cmd = new SqlCommand(strQuery);

        cmd.Parameters.Add("@Name", SqlDbType.VarChar).Value = filename;

        cmd.Parameters.Add("@ContentType", SqlDbType.VarChar).Value

          = contenttype;

        cmd.Parameters.Add("@Data", SqlDbType.Binary).Value = bytes;

        InsertUpdateData(cmd);

        lblMessage.ForeColor = System.Drawing.Color.Green;  

        lblMessage.Text = "File Uploaded Successfully";

    }

    else

    {

        lblMessage.ForeColor = System.Drawing.Color.Red;   

        lblMessage.Text = "File format not recognised." +

          " Upload Image/Word/PDF/Excel formats";

    }

}

<强>更新

private Boolean InsertUpdateData(SqlCommand cmd)

{

    String strConnString = System.Configuration.ConfigurationManager

    .ConnectionStrings["conString"].ConnectionString;

    SqlConnection con = new SqlConnection(strConnString);

    cmd.CommandType = CommandType.Text;

    cmd.Connection = con;

    try

    {

        con.Open();

        cmd.ExecuteNonQuery();

        return true;

    }

    catch (Exception ex)

    {

        Response.Write(ex.Message);

        return false;

    }

    finally

    {

        con.Close();

        con.Dispose();

    }

}

答案 1 :(得分:0)

我通过这样做得到了它:

If (String.IsNullOrEmpty(validationMessage)) Then
      cmd = New SqlCommand("", conn)

            Dim imageData As Byte()
            Dim sFilePath As String = fuSelectedFile.PostedFile.FileName
            Dim ext As String = Path.GetExtension(sFilePath)
            Dim sFileName As String
            Dim sFileType As String

            'upload file to DB
            If (RadioButtonList1.SelectedValue = "0") Then
                If Not String.IsNullOrEmpty(sFilePath) Then
                    If (ext = ".jpeg" Or ext = ".pdf" Or ext = ".jpg") Then

                        Try
                            'Read Image Bytes into a byte array 
                            'Initialize SQL Server Connection 
                            If conn.State = ConnectionState.Closed Then
                                conn.Open()
                            End If

                            'Convert File to bytes Array
                            'Initialize byte array with a null value initially. 
                            Dim data As Byte() = Nothing
                            'Use FileInfo object to get file size. 
                            Dim fInfo As New FileInfo(sFilePath)
                            Dim numBytes As Long = fInfo.Length
                            'Open FileStream to read file 
                            Dim fStream As New FileStream(sFilePath, FileMode.Open, FileAccess.Read)
                            'Use BinaryReader to read file stream into byte array. 
                            Dim br As New BinaryReader(fStream)
                            'When you use BinaryReader, you need to supply number of bytes to read from file. 
                            'In this case we want to read entire file. So supplying total number of bytes. 
                            imageData = br.ReadBytes(CInt(numBytes))

                            sFileName = System.IO.Path.GetFileName(sFilePath)
                            sFileType = System.IO.Path.GetExtension(sFilePath)


                            'Set insert query 


                            'Execute the Query
                            cmd.ExecuteNonQuery()

                        Catch ex As Exception
                            validationMessage = "The file could not be uploaded. The following error occured: " & ex.Message
                            Console.WriteLine(ex.Message)
                        End Try
                    Else
                        validationMessage = "Jpeg or PDF files only!"
                    End If

                Else
                    validationMessage = "No file selected!"
                End If

            End If
        End If
相关问题