简体   繁体   中英

Create a transaction for sending data to the server

I want post pictures and data. If the error occurred. None of them should be done. But the problem is that the photo is stored on the server. Or data are stored.

and the name of photo must be ID news. i know how write store procedure but i don't know how write sending picture to the server and send address of picture to the database with transaction. that mean if ocures Do not save any data.

this is part of code

this is sending news

            cmd.Parameters.Add(new SqlParameter("@title", TextBox1.Text));
        cmd.Parameters.Add(new SqlParameter("@day", DateTime.Now.Day));
        cmd.Parameters.Add(new SqlParameter("@month", DateTime.Now.Month));
        cmd.Parameters.Add(new SqlParameter("@year", DateTime.Now.Year));
        cmd.Parameters.Add(new SqlParameter("@text", TextBox2.Text));
        cmd.Parameters.Add(new SqlParameter("@id_writer", Session["is_login"]));

and this is sending picture to the server

          //insert pic  adress in db
        //1-get web path
        string path = Server.MapPath(".") + "\\newspic\\";
        //2-get and check file etention
        string[] validExt = { ".jpg", ".gif", ".png" };
        string ext = System.IO.Path.GetExtension(FileUpload1.PostedFile.FileName);
        if (Array.IndexOf(validExt, ext.ToLower()) < 0)
        {
            //the file dosent exsist in this palce
            return;
        }
        //3-get and check file size
        long size = FileUpload1.PostedFile.ContentLength;
        size /= 1024;
        if (size > 2024)
        {
            //the size of pic is large
            return;
        }
        if (size == 0)
        {
            //you dont send file
            return;
        }
        //4-get file name
        string filename = System.IO.Path.GetFileName(FileUpload1.PostedFile.FileName);

        //6-savefile to server
        FileUpload1.PostedFile.SaveAs(path + filename);

and this is sending address of pic to the database

  cmd.Parameters.Add(new SqlParameter("@pic", path + filename));

From what I can gather essentially you want to

public void UploadFile()
{
    var file      = FileUpload1.PostedFile;
    var title     = TextBox1.Text;
    var text      = TextBox2.Text;
    var id_writer = Session["is_login"];
    var filename  = string.Empty;

    if (TryUploadFile(file, out filename))
    {
        if (!TryInsertFile(title, text, id_writer, filename))
        {
            File.Delete(filename);
        }
    }
}

You seem to already have most of it, so with just some tweaking you end up with something like

public bool IsValid(HttpPostedFile file)
{
    var validExtensions = { ".jpg", ".gif", ".png" };

    var fileExtension = System.IO.Path.GetExtension(file.FileName);

    if (Array.IndexOf(validExtensions, fileExtension.ToLower()) < 0)
    {
        return false;
    }

    var size = file.ContentLength / 1024;

    if (size == 0 || size > 2024)
    {
        return false;
    }
}

private bool TryUploadFile(HttpPostedFile file, out string filename)
{
    var path = Server.MapPath(".") + "\\newspic\\";

    filename = path + System.IO.Path.GetFileName(file.FileName);        

    if (!IsValid(file))
    {
        return false;
    }

    try 
    {
        file.SaveAs(filename);
    }
    catch (HttpException)
    {
        return false;
    }
}

private bool TryInsertFile(string title, string text, string id_writer, string filename)
{
    using (var conn = new SqlConnection("<connectionString>"))
    {    
        try
        {            
            var now = DateTime.Now;

            conn.Open();

            var qry = "INSERT INTO tbl (title, day, month, year, text, id_writer, pic)" + 
                      "VALUES (@title, @day, @month, @year, @text, @id_write, @pic)"

            var cmd = new SqlCommand()

            cmd.Parameters.Add(new SqlParameter("@title", title));
            cmd.Parameters.Add(new SqlParameter("@day", now.Day));
            cmd.Parameters.Add(new SqlParameter("@month", now.Month));
            cmd.Parameters.Add(new SqlParameter("@year", now.Year));
            cmd.Parameters.Add(new SqlParameter("@text", text));
            cmd.Parameters.Add(new SqlParameter("@id_writer", id_writer));
            cmd.Parameters.Add(new SqlParameter("@pic", filename));

            cmd.ExecuteNonQuery();
        }
        catch (SqlException)
        {
            return false;
        }
    }
}

Edit:

Because the filename is dependant on the identity of the inserted row then in a single method using an explicit database transaction.

private void UploadPicture(HttpPostedFile file, string title, string text, string id_writer)
{
    if (!IsValid(file)) return;

    using (var conn = new SqlConnection(/* connection string */))
    {    
        conn.Open();

        // begin a transaction which will be rolled back if not committed
        using (var tx = conn.BeginTransaction())
        {            
            var now = DateTime.Now;                

            var insert = "INSERT INTO tbl (title, day, month, year, text, id_writer, pic)" + 
                         "VALUES (@title, @day, @month, @year, @text, @id_write, @pic);" +
                         "SELECT SCOPE_IDENTITY();";

            var update = "UPDATE tbl SET pic = @pic WHERE id = @id";

            var insertCommand = new SqlCommand(insert);

            var updateCommand = new SqlCommand(update);

            // insert the row for the uploaded file
            insertCommand.Parameters.Add(new SqlParameter("@title", title));
            insertCommand.Parameters.Add(new SqlParameter("@day", now.Day));
            insertCommand.Parameters.Add(new SqlParameter("@month", now.Month));
            insertCommand.Parameters.Add(new SqlParameter("@year", now.Year));
            insertCommand.Parameters.Add(new SqlParameter("@text", text));
            insertCommand.Parameters.Add(new SqlParameter("@id_writer", id_writer));

            // get the identity of the inserted row
            var identity = Convert.ToInt32(insertCommand.ExecuteScalar());

            // get the filename appending the identity
            var path = Server.MapPath(".") + "\\newspic\\";

            var filename =  path + System.IO.Path.GetFileName(file.FileName) + identity;

            // update the row with the filename
            updateCommand.Parameters.Add(new SqlParameter("@pic", filename));
            updateCommand.Parameters.Add(new SqlParameter("@id", identity));

            updateCommand.ExecuteNonQuery();

            // save the file
            file.SaveAs(filename);

            // all done so commit
            tx.Commit();
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM