在ASP.net中使用文件上载上传文件

时间:2013-07-07 06:50:58

标签: c# asp.net

我将代码写入上传文件保存在项目根目录中。如何将此更改为将路径保存到数据库,将文件更改为单独的文件夹

protected void UploadButton_Click(object sender, EventArgs e)
{
    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 status: The file could not be uploaded. The following error occured: " + ex.Message;
        }
    }
}

1 个答案:

答案 0 :(得分:1)

protected void UploadButton_Click(object sender, EventArgs e)
{
    if (FileUploadControl.HasFile) {
        try {
            string filename = Path.GetFileName(FileUploadControl.FileName);

            FileUploadControl.SaveAs(Server.MapPath("~/") + filename);
            saveImgPathToDB(filename, 3);

            StatusLabel.Text = "Upload status: File uploaded!";
        } catch (Exception ex) {
            StatusLabel.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
        }
    }
}

private void saveImgPathToDB(string path, int recordID)
{
    using (sqlconnection db = new sqlconnection("your_connection_string")) {
        using (sqlcommand cmd = new sqlcommand("INSERT INTO photo_table (PhotoPath) VALUES (@path) WHERE someId=@someid", cn)) {
            cmd.parameters.addwithvalue("@path", path);
            cmd.parameters.addwithvalue("someid", recordID);
            cmd.connection.open();

            try {
                cmd.executenonquery();

            }
        }
    }
}