【问题标题】:Upload Image with FileUpload and Stock in database在数据库中使用 FileUpload 和 Stock 上传图像
【发布时间】:2014-05-30 12:13:29
【问题描述】:

我想用 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);

这是什么原因造成的?

谢谢

【问题讨论】:

标签: asp.net file-upload webforms


【解决方案1】:

试试这个代码上传:

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

【讨论】:

  • MohamedGooner 我如何将文件插入数据库我正在使用框架实体 f.photo = FileUpload1.HasFile.ToString();
  • 您可以使用 SQL 语句插入数据库。使用一个简单的insert sql语句,你可以在网上看到一些关于编写sql语句的解释。
【解决方案2】:

您的错误发生在这里:

string filePath =  FileUpload1.PostedFile.FileName;

如果 this 为 null(它是)- 那么您对 ​​this 的调用:

string filename = Path.GetFileName(filePath);

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

尝试使用调试器单步执行以了解发生这种情况的原因。

【讨论】:

    【解决方案3】:

    稍微改一下代码,如下

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多