3

I wrote the code to upload the file and save in project root directory. How can I change this to save the path into database and the files into a separate folder from project?

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

            }
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.