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 に答える