Click here to Skip to main content
14,298,065 members
Rate this:
Please Sign up or sign in to vote.
See more:
Hi guys my fileupload in asp doesnt seemk to work it keep returning a null value after picking the file when I check in the Debugger can someone please show me where im going wrong

protected void btnSend_Click(object sender, EventArgs e)
    {
        FileUpload fileuploadExcel = new FileUpload();
        if ((fileuploadExcel.PostedFile != null) && (fileuploadExcel.PostedFile.ContentLength > 0))
        {
            string fn = System.IO.Path.GetFileName(fileuploadExcel.PostedFile.FileName);
            string SaveLocation = Server.MapPath("Data") + "\\" + fn;
            try
            {
                fileuploadExcel.PostedFile.SaveAs(SaveLocation);
                Response.Write("The file has been uploaded.");
            }
            catch (Exception ex)
            {
                Response.Write("Error: " + ex.Message);
                //Note: Exception.Message returns detailed message that describes the current exception. 
                //For security reasons, we do not recommend you return Exception.Message to end users in 
                //production environments. It would be better just to put a generic error message. 
            }
        }
        else
        {
            Response.Write("Please select a file to upload.");
        }
}
Posted
Updated 3-Sep-12 22:47pm
v2
Rate this:
Please Sign up or sign in to vote.

Solution 1

Hello,

Is File upload control inside the Update panel?? if it is so then it will not work, either you have to trigger event or put file upload control out side update panel.
   
Comments
mrDivan 4-Sep-12 4:42am
   
Hi here is my other code could you please tell me where would u put the fileupload

<%@ Page language="c#" Codebehind="WebForm1.aspx.cs" AutoEventWireup="false" Inherits="CSharpUpload.WebForm1" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
<HEAD>
<title>WebForm1</title>
<meta name="GENERATOR" Content="Microsoft Visual Studio 7.0">
<meta name="CODE_LANGUAGE" Content="C#">
<meta name=vs_defaultClientScript content="JavaScript">
<meta name=vs_targetSchema content="http://schemas.microsoft.com/intellisense/ie5">
</HEAD>
<body MS_POSITIONING="GridLayout">
<form id="Form1" method="post" enctype="multipart/form-data" runat="server">
<INPUT type=file id=File1 name=File1 runat="server" >
<br>
<input type="submit" id="Submit1" value="Upload" runat="server" NAME="Submit1">
</form>


</body>
</HTML>
Rate this:
Please Sign up or sign in to vote.

Solution 2

You have the wrong code. If you have FileUpload control in .aspx page then what is need to create an object for that. Here is your modified code and tested ok. Hope you will get right answer. :-

.aspx page
-------------------
<asp:FileUpload ID="fileuploadExcel" runat="server" />
    <asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />


code behind (.aspx.cs)
--------------------------
protected void Button1_Click(object sender, EventArgs e)
    {
        if ((fileuploadExcel.PostedFile != null) && (fileuploadExcel.PostedFile.ContentLength > 0))
        {
            string fn = System.IO.Path.GetFileName(fileuploadExcel.PostedFile.FileName);
            string SaveLocation = Server.MapPath("Data") + "\\" + fn;
            try
            {
                fileuploadExcel.PostedFile.SaveAs(SaveLocation);
                Response.Write("The file has been uploaded.");
            }
            catch (Exception ex)
            {
                Response.Write("Error: " + ex.Message);
                //Note: Exception.Message returns detailed message that describes the current exception.
                //For security reasons, we do not recommend you return Exception.Message to end users in
                //production environments. It would be better just to put a generic error message.
            }
        }
        else
        {
            Response.Write("Please select a file to upload.");
        }
    }


If you will get perfect answer then Mark as answer for future reference.
   
v2
Comments
mrDivan 4-Sep-12 4:51am
   
sorry here is the right code


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

<!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 id="Head1" runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<table>
<tr>
<td>
<span style="color: Red">*</span>Attach Excel file
</td>
<td>
<asp:fileupload ID ="fileuploadExcel" runat="server" />
</td>
</tr>
<tr>
<td></td>
<td>
<asp:Button ID="btnSend" runat="server" Text="Export" onclick="btnSend_Click" />
</td>
</tr>
</table>
<asp:GridView ID="GridView1" runat="server">

</div>
</form>
</body>
</html>
mrDivan 4-Sep-12 5:06am
   
i keep getting this error
The name 'fileuploadExcel' does not exist in the current context
Anuja Pawar Indore 5-Sep-12 4:42am
   
Add your code to your question, use improve question link. No need to paste that again and again
Sunil Kumar Pandab 5-Sep-12 4:24am
   
Your .aspx code is right. But code behind (.aspx.cs) is wrong what you posted in your question. Take my given code put inside your btnSend_Click method, it will work fine. Because it is tested ok.
Kunal Chowdhury «IN» 27-May-13 6:17am
   
Hi Sunil,

I tried the mentioned solution in my project but the above code is not working. I am getting fileuploadExcel.PostedFile as NULL. My file upload control is outside the UpdateManager. Now what to do? Looking for a solution. Please suggest.
Rate this:
Please Sign up or sign in to vote.

Solution 3

Try this
I using html fileupload
protected void btnSend_Click(object sender, EventArgs e)
{
Request.Files("File1").SaveAs("path")

}


If using asp.net file upload

then
Dont use this line
FileUpload fileuploadExcel = new FileUpload();
   
v2
Rate this:
Please Sign up or sign in to vote.

Solution 6

I fixed it thanks autoeventwire was set to false
   
Rate this:
Please Sign up or sign in to vote.

Solution 4

protected void btnSend_Click(object sender, EventArgs e)
    {
        String strConnection = "Data Source=DIVAN-DT;Initial Catalog=Database1;Integrated Security=True";
        //file upload path
        
        string path = fileuploadExcel.PostedFile.FileName;//this where I get my error
        //Create connection string to Excel work book
        string excelConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=Excel 12.0;Persist Security Info=False";
        //Create Connection to Excel work book
        OleDbConnection excelConnection = new OleDbConnection(excelConnectionString);
        //Create OleDbCommand to fetch data from Excel
        OleDbCommand cmd = new OleDbCommand("Select [ID],[Name],[Designation] from [Sheet1$]", excelConnection);
        excelConnection.Open();
        OleDbDataReader dReader;
        dReader = cmd.ExecuteReader();
        SqlBulkCopy sqlBulk = new SqlBulkCopy(strConnection);
        //Give your Destination table name
        sqlBulk.DestinationTableName = "Excel_table";
        sqlBulk.WriteToServer(dReader);
        excelConnection.Close();


<![CDATA[<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>
   
v2
Comments
pradiprenushe 4-Sep-12 5:41am
   
haveu used file upload control in design?
Rate this:
Please Sign up or sign in to vote.

Solution 5

this is my excel upload using vb.net

you can use a convertor to conver it to c# if you are unsure of how to do it
<asp:Panel ID="PanelUpload" runat="server" Visibile="False">
        <asp:FileUpload ID="FileUploadExcel" runat="server" />
        <br />
        Please select an Excel File to upload<br />
        <asp:Label ID="LabelUpload" runat="server" Text="">
        </asp:Label>
    </asp:Panel>

code behind...
Protected Sub ButtonUploadFile_Click(ByVal sender As Object, ByVal e As System.EventArgs) _
            Handles ButtonUploadFile.Click
        PanelUpload.Visible = True
        btnNo.Visible = False
        btnYes.Visible = False
        btnSave.Visible = False


        'check to see if the SiteTemplate file already exists. if so delete it
        If FileUploadExcel.HasFile Then
            Try
                'alter path for your project

                FileUploadExcel.SaveAs(Server.MapPath("~/SiteTemplate.xls"))
                FileUploadExcel.Dispose()
                LabelUpload.Text = "Upload File Name: " & _
                     FileUploadExcel.PostedFile.FileName & "<br>" & _
                     "Type: " & _
                     FileUploadExcel.PostedFile.ContentType & _
                     " File Size: " & _
                     FileUploadExcel.PostedFile.ContentLength & " kb<br>"


                ButtonUploadFile.Enabled = False
                ButtonView.Enabled = True

                'save the file to a different location with the time and date on the end of the file at upload
                Dim sFileDir As String = "C:\xxxx\xxxx\My Documents\"
                Dim sFileName As String = System.IO.Path.GetFileName(FileUploadExcel.PostedFile.FileName)

                Dim TLDateTime As String
                Dim TLDay As String
                Dim TLMonth As Integer
                Dim TLYear As Integer
                Dim TLHour As Integer
                Dim TLMinute As Integer
                Dim TLDate As String
                Dim TLTime As String
                TLDay = DateTime.Now.Day
                TLMonth = DateTime.Now.Month
                TLYear = DateTime.Now.Year
                TLHour = DateTime.Now.Hour
                TLMinute = DateTime.Now.Minute
                TLDate = TLDay.ToString + "-" + TLMonth.ToString + "-" + TLYear.ToString
                TLTime = TLHour.ToString + "-" + TLMinute.ToString
                TLDateTime = TLDate + "_" + TLTime

                'delete the extension on the file name so you do not have two "." in your file
                sFileName = Left([sFileName], InStrRev([sFileName], ".") - 1)
                FileUploadExcel.PostedFile.SaveAs(sFileDir + sFileName + "_" + TLDateTime + ".xls")
                FileUploadExcel.Dispose()
            Catch ex As Exception
                LabelUpload.Text = "Error: " & ex.Message.ToString
            End Try
        Else
            LabelUpload.Text = "Please select a file to upload."
        End If


    End Sub


the next bit is for uploading a pdf file but you can alter for excel
If FileUpload1.HasFile = False And FileUpload2.HasFile = False Then
            Label1.Text = "Please select file to upload"
        Else

            If FileUpload1.HasFile Then
                If (FileUpload1.PostedFile.ContentLength < 3145728) Then
                    If Not Request.QueryString("siteDataID") Is Nothing Then
                        Dim fileLength As Integer = FileUpload1.PostedFile.ContentLength
                        Dim bytfile(fileLength) As Byte
                        FileUpload1.PostedFile.InputStream.Read(bytfile, 0, fileLength)

                        ' Insert the image and file name into the database
                        Dim connection As New SqlConnection(ConfigurationManager.ConnectionStrings("connectionsstring").ConnectionString)

                        Try
                            connection.Open()
                             Dim cmd As New SqlCommand("UPDATE tblxxx " & _
                            " SET [xxxPDF1]=@file, PDF1Name=@filename" & _
                           " WHERE xxxdatid=@xxxdataid", connection)
                            cmd.Parameters.AddWithValue("@file", bytfile)
                            cmd.Parameters.AddWithValue("@xxxdataID", Request.QueryString("siteDataID"))
                            cmd.Parameters.AddWithValue("@filename", FileUpload1.PostedFile.FileName)
                            'cmd.Parameters.AddWithValue("@fileuploadedby", Session("UserID"))
                            cmd.ExecuteNonQuery()

                            Label1.Text = FileUpload1.PostedFile.FileName + " : Uploaded Successfully"

                        Catch ex As Exception

                            Label1.Text = "File Not Uploaded" & ex.ToString
                        Finally
                            connection.Close()
                        End Try
                        '               Label1.Visible = True

                    End If
                Else
                    Label3.Visible = True
                    Label3.Text = "ERROR: File " & FileUpload1.PostedFile.FileName & " not uploaded. Size must not exceed 3MB."

                End If

            End If
   
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month



CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100