-2

I want to Upload a Image with FileUpload and store it in database and the code for it is this :

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
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
    f.photo = Convert.ToString(FileUpload1.FileBytes);
    Label1.ForeColor = System.Drawing.Color.Green;
    Label1.Text = "File Uploaded Successfully";
}

but I get this error:

error :Object reference not set to an instance of an object.`
in 
string filename = Path.GetFileName(filePath);

What is causing this?

thanks

Biswanath
  • 9,075
  • 12
  • 44
  • 58
  • possible duplicate of [What is a NullReferenceException and how do I fix it?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Ondrej Tucny Aug 27 '15 at 21:21

3 Answers3

0

Your error is occuring here:

string filePath =  FileUpload1.PostedFile.FileName;

If this is null (which it is) - then your call to this:

string filename = Path.GetFileName(filePath);

Will give you that error, as you're passing a string object which hasn't been initialised correctly.

Try stepping through with the debugger to see why this is occuring.

Chris L
  • 2,262
  • 1
  • 18
  • 33
0

change the code a bit, as follows

//on upload button click
  if(FileUploadControl.HasFile)
    {
        try
        {
            string filename = Path.GetFileName(FileUploadControl.FileName);
            FileUploadControl.SaveAs(Server.MapPath("~/") + filename);
            StatusLabel.Text = "Upload status: File uploaded!";
        }
        catch(Exception ex)
        {
            StatusLabel.Text = "Upload error:" + ex.Message;
        }
    }

http://www.codeproject.com/Articles/1757/File-Upload-with-ASP-NET

koolprasad2003
  • 299
  • 3
  • 23
0

try this code for uploading:

string strRealPath = Request.PhysicalApplicationPath;
if(FileUpload1.HasFile)
{
    string fileName = FileUpload1.FileName; 
    FileUpload1.SaveAs(strRealPath + fileName);
    //Now insert the file into the database.
}
musay
  • 88
  • 1
  • 8
  • MohamedGooner how i can insert the file into database i am using framwork entity f.photo = FileUpload1.HasFile.ToString(); – user3537566 May 30 '14 at 14:38
  • You can use SQL statement for inserting into your database. Use a simple insert sql statement, you can see some explainations on the internet for writing sql statements. – musay May 31 '14 at 14:58