3

我编写了代码来上传文件保存在项目根目录中。如何更改它以将路径保存到数据库中并将文件保存到项目的单独文件夹中?

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

1 回答 1

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();

            }
        }
    }
}
于 2013-07-07T11:34:39.943 回答