0

I have a file upload control and an "upload" button in my page. I am trying to write codes for uploading word files to my db.

Please find below the code:-

if (FileUpload1.HasFile)
            {

                string fileextention = System.IO.Path.GetExtension(FileUpload1.FileName);
                if (fileextention == ".doc" || fileextention == ".docx")
                {
                    string filename = System.IO.Path.GetFileName(FileUpload1.FileName);
                    //Upload file
                    FileUpload1.SaveAs(Server.MapPath("~/DocumentCollection/")  + filename);
                    string fullpath = "DocumentCollection/" + filename;
                    string query = "insert into dbo.DocumentMaster(Name,Path) values(" + filename + "," + "DocumentCollection/" + filename + ");";
                    SqlDataAdapter objda = new SqlDataAdapter(query, objcon);


                    objcon.Open();
                    objda.SelectCommand.ExecuteNonQuery();
                    objcon.Close();
                    Label2.Text = " successfully uploaded.";

                }
                else
                {
                    Label2.Text = "Selected File is not a word document file.";
                }

My DB structure:-

CREATE TABLE [dbo].[DocumentMaster](
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [Name] [varchar](100) NULL,
    [Path] [varchar](100) NULL,
 CONSTRAINT [PK_DocumentMaster] PRIMARY KEY CLUSTERED 
(
    [Id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

But I am encountering an error when i am trying to upload a word.docx file. The word.docx has been successfully uploaded to the DocumentCollection folder in my application.

The multi-part identifier "word.docx" could not be bound. Invalid column name 'DocumentCollection'. The multi-part identifier "word.docx" could not be bound.

Please help me.

4

1 回答 1

0

这本质上就是您发送到数据库的内容:

insert into dbo.DocumentMaster(Name,Path) values(word.docx,DocumentCollection/word.docx)

如您所见,您没有为值部分发送“字符串”。

你可以这样做:

string query = "insert into dbo.DocumentMaster(Name,Path) values('" + filename + "','" + "DocumentCollection/" + filename + "');";

因此,您会得到以下查询:

insert into dbo.DocumentMaster(Name,Path) values('word.docx','DocumentCollection/word.docx')

来解决你的问题,但你仍然很容易受到 SQL 注入的影响。我强烈建议您改用参数化查询。

于 2013-07-03T08:55:26.120 回答