0

I'm creating a form with "Upload" control by HTML input type="file"

Here is my html code:

<form id="form1" runat="server" enctype="multipart/form-data">
    <div class="form-group">
        <asp:label ID="Label1" runat="server" For="message-text" class="col-form-label">Transaction Slip:</asp:label><br />
        <input type="file" name="FileUpload" class="btn btn-light" accept="image/*"/>
    </div>
</form>

And the .cs behind code like below:

protected void btnSubmit_Clicked(object sender, EventArgs e)
{
    HttpPostedFile postedFile = Request.Files["FileUpload"];
    string filePath = Server.MapPath("~/TransacSlip/") + Path.GetFileName(postedFile.FileName);
    postedFile.SaveAs(filePath);
}

But I was getting the error below:

Server Error in '/' Application. Object reference not set to an instance of an object.

Error Line:

Line 78: string filePath = Server.MapPath("~/TransacSlip/") + Path.GetFileName(postedFile.FileName);

Did anyone know how to solve this problem ? Many Thanks ~

5
  • 1
    Possible duplicate of What is a NullReferenceException, and how do I fix it? Commented Jan 23, 2019 at 10:51
  • @Izzy Hi, Thanks for reply. I was already added an image by using the HTML input control, meaning it shoudn't be a Null value, so if let say it's really Null value detected, may I know how to let system detect it's value due to it was already have an image in the html input before I run this code to storing image in my server path Commented Jan 23, 2019 at 10:59
  • You can use postedFile.ContentLength > 0 to check file exists or not, my friend :)) Commented Jan 23, 2019 at 11:02
  • @TeoLawrence, check my answer. I have provided two different approaches and both will solve your problem. Commented Jan 23, 2019 at 11:22
  • @TeoLawrence, Please mark the answer for the benefit of all, if it has satisfied your requirements. Commented Jan 23, 2019 at 12:04

3 Answers 3

1

Add runat="server" to the html input of type file control as in code below, then you will have a posted file in code-behind else Request.Files collection is going to be empty in code-behind.

<input type="file" name="FileUpload" class="btn btn-light" accept="image/*" runat="server"/>

Right now since no Files are getting posted, so postedFile variable is null and therefore, when you invoke a method or access a property on this variable it will throw a null reference exception. In your case postedFile.FileName will cause this exception in your code-behind.

Alternate Solution:

If you wanted to not use runat="server" attribute for input control of file type, then make sure your form in the page has the enctype attribute set to multipart/form-data as in code below. This will also solve your problem. You don't need to add runat="server" attribute if you follow this approach.

<form id="form1" runat="server" enctype="multipart/form-data">
Sign up to request clarification or add additional context in comments.

5 Comments

Hi Sunil, My code above are using enctype="multipart/form-data" at the <form> already, not work, and just now I tried to put runat=server on the input control too, doesn't work too...
It look like the code get a null value from input control, but I'm actually choosed an image by using the control (and I can see the picture thumbnail too on the control) before I run "btnSubmit_Clicked"
The reason you get a null value is because you are missing the parts mentioned in my answer. When you click on submit button then data i.e. image file gets submitted to back end server provided you use runat="server" or set the form's enctype attribute as described in my answer. If you don't use any of the possible solutions, then only in browser you can see the image but its not sent to the back end server.
I solved my problem, it was because I accidently added one more <form> inside the <form id="form1" runat="server" enctype="multipart/form-data">
Ok. Great. Just remember that if you used runat="server" attribute then you would not need encytype. Also, its always a good practice to give an id to to your input file element. The id need not be the same as the name attribute.
1

I'm post the full solution I used here for other people who need this function also.

Code in HTML/ASP.Net (Remember to put enctype="multipart/form-data")

<form id="form1" runat="server" enctype="multipart/form-data">
    <input type="file" name="FileUpload" class="btn btn-light" accept="image/*"/>
    <asp:Button ID="TestButton" runat="server" Text="Button" OnClick="TestButton_Clicked" />
</form>

Code Behind (c#)

using System.IO;

protected void TestButton_Clicked(object sender, EventArgs e)
{
    //To get the file from HTML Input File
    HttpPostedFile postedFile = Request.Files["FileUpload"];

    //String your relative folder path
    string folderPath = Server.MapPath("~/FolderName/");

    //Check if your folder is exist or not, if not then created folder automatically
    if (!Directory.Exists(folderPath))
    {
        Directory.CreateDirectory(folderPath);
    }

    //Check did your control have image uploaded
    if (postedFile != null && postedFile.ContentLength > 0)
    {
        //To prevent duplicated name (accidently replace), using GUID code to store your image
        string GUIDCode = System.Guid.NewGuid().ToString("N");
        string filePath = folderPath + GUIDCode + ".jpg";
        postedFile.SaveAs(filePath);
    }
    else if (postedFile == null && postedFile.ContentLength <= 0)
    {
        // Do your thing when control have no image uploaded
    }
}

Comments

0

Please try this code

//Access the File using the Name of HTML INPUT File.
HttpPostedFile postedFile = Request.Files["FileUpload"];

//Check if File is available.
if (postedFile != null && postedFile.ContentLength > 0)
{
   //Save the File.
   string filePath = Server.MapPath("~/TransacSlip/") + Path.GetFileName(postedFile.FileName);
   postedFile.SaveAs(filePath);
   lblMessage.Visible = true;
}

1 Comment

@Prashant Pimpale I tried this code before to catch wether the control has value or not, It look like the code get a null value from input control, but I'm actually choosed an image by using the control (and I can see the picture thumbnail too on the control) before I run "btnSubmit_Clicked"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.