使用FileUpload和Stock上传数据库

时间:2014-05-30 12:13:30

标签: asp.net file-upload webforms

我想使用FileUpload上传图像并将其存储在数据库中,其代码如下:

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";
}

但是我收到了这个错误:

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

造成这种情况的原因是什么?

感谢

3 个答案:

答案 0 :(得分:0)

您的错误发生在此处:

string filePath =  FileUpload1.PostedFile.FileName;

如果这是null(它是) - 那么你对此的调用:

string filename = Path.GetFileName(filePath);

当你传递一个尚未正确初始化的字符串对象时,会给你这个错误。

尝试使用调试器逐步查看发生这种情况的原因。

答案 1 :(得分:0)

稍微更改一下代码,如下所示

//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

答案 2 :(得分:0)

尝试使用此代码进行上传:

string strRealPath = Request.PhysicalApplicationPath;
if(FileUpload1.HasFile)
{
    string fileName = FileUpload1.FileName; 
    FileUpload1.SaveAs(strRealPath + fileName);
    //Now insert the file into the database.
}