File upload for ajax

Keywords: JSON Database SQL JQuery

Form Upload File

Traditional file uploads are via form forms. As the saying goes, solutions that don't focus on actual problems are fake, so I'll simulate a user registration function.
Look at the following code:

[HttpPost]
public ActionResult Upload(string username, string password, string realName, string address, HttpPostedFileBase picture)
{
    //Save File
    string fileName = Guid.NewGuid().ToString() + ".png";
    var realPath = Server.MapPath("/Upload/" + fileName);
    picture.SaveAs(realPath);

    //Update database
    using(SqlConnection conn = new SqlConnection("Data Source=DESKTOP-2HL1HGR\\SQL2014;Initial Catalog=TestDemo;Integrated Security=True"))
    {
        conn.Open();
        string sql = string.Format("INSERT INTO tb_user (Username, Password, RealName, Address, FileName) VALUES ('{0}', '{1}', '{2}', '{3}', '{4}')",
            username, password, realName, address, fileName);
        SqlCommand cmd = new SqlCommand(sql, conn);
        int result = cmd.ExecuteNonQuery();
        if(result > 0)
        {
            return Json("Success");
        }else
        {
            return Json("Fail");
        }
    }
}
<h1>User registration</h1>
<form action="/Test/Upload" method="post" enctype="multipart/form-data">
    <table class="table table-hover">
        <tr>
            <td><b>User Name</b></td>
            <td><input type="text" id="username" name="username" class="form-control" /></td>
        </tr>
        <tr>
            <td><b>User Password</b></td>
            <td><input type="password" id="password" name="password" class="form-control" /></td>
        </tr>
        <tr>
            <td><b>Real name</b></td>
            <td><input type="text" id="realName" name="realName" class="form-control" /></td>
        </tr>
        <tr>
            <td><b>Home Address</b></td>
            <td><input type="text" id="address" name="address" class="form-control" /></td>
        </tr>
        <tr>
            <td><b>User Portrait</b></td>
            <td><input type="file" id="picture" name="picture" class="form-control" /></td>
        </tr>
        <tr>
            <td colspan="2">
                <input type="submit" id="btnEdit" class="btn btn-primary" value="register" />
                <input type="reset" class="btn btn-danger" value="Reset" />
            </td>
        </tr>
    </table>
</form>



Forms allow you to upload files smoothly, but the obvious drawback is that callback functions cannot be executed on pages, so we usually use ajax for file upload.

ajax file upload

For easy reference we define a model class User

public class User
{
    public int Id { get; set; }
    public string Username { get; set; }
    public string Password { get; set; }
    public string RealName { get; set; }
    public string Address { get; set; }
}

Then define the parameters as User and file in the method of controlling the class

[HttpPost]
public ActionResult Upload(User user, HttpPostedFileBase FileName)
{
    //Save File
    string fileName = Guid.NewGuid().ToString() + ".png";
    var realPath = Server.MapPath("/Upload/" + fileName);
    FileName.SaveAs(realPath);
    //Update database
    using (SqlConnection conn = new SqlConnection("Data Source=DESKTOP-2HL1HGR\\SQL2014;Initial Catalog=TestDemo;Integrated Security=True"))
    {
        conn.Open();
        string sql = string.Format("INSERT INTO tb_user (Username, Password, RealName, Address, FileName) VALUES ('{0}', '{1}', '{2}', '{3}', '{4}')",
            user.Username, user.Password, user.RealName, user.Address, fileName);
        SqlCommand cmd = new SqlCommand(sql, conn);
        int result = cmd.ExecuteNonQuery();
        if(result > 0)
        {
            return Json("Success");
        }else
        {
            return Json("Fail");
        }
    }
}

The point is that the foreground method needs to instantiate a FormData class to hold the form's data, and set processData and contentType to false in ajax, otherwise it won't jump to the background control layer.

<h1>User registration</h1>
<form id="form1">
    <table class="table table-hover">
        <tr>
            <td><b>User Name</b></td>
            <td><input type="text" id="Username" name="Username" class="form-control" /></td>
        </tr>
        <tr>
            <td><b>User Password</b></td>
            <td><input type="password" id="Password" name="Password" class="form-control" /></td>
        </tr>
        <tr>
            <td><b>Real name</b></td>
            <td><input type="text" id="RealName" name="RealName" class="form-control" /></td>
        </tr>
        <tr>
            <td><b>Home Address</b></td>
            <td><input type="text" id="Address" name="Address" class="form-control" /></td>
        </tr>
        <tr>
            <td><b>User Portrait</b></td>
            <td>
                <input type="file" id="FileName" name="FileName" class="form-control" />
            </td>
        </tr>
        <tr>
            <td colspan="2">
                <input type="button" id="btnConfirm" class="btn btn-primary" value="register" />
                <input type="reset" class="btn btn-danger" value="Reset" />
            </td>
        </tr>
    </table>
</form>
<script>
    $(function () {
        $("#btnConfirm").click(function () {
            var formData = new FormData();
            formData.append("Username", $("#Username").val());
            formData.append("Password", $("#Password").val());
            formData.append("RealName", $("#RealName").val());
            formData.append("Address", $("#Address").val());
            formData.append("FileName", $("#FileName")[0].files[0]);
            $.ajax({
                url: "/Test/Upload",
                type: "post",
                dataType: "json",
                data: formData,
                processData: false, // Tell jQuery not to process the sent data, it must be false here to serialize the data parameters
                contentType: false, // Tell jQuery not to set the Content-Type request header
                success: function (result) {
                    if (result == "Success") {
                        console.log("login was successful!");
                    } else {
                        console.log("login has failed!");
                    }
                }
            })
        })
    })
</script>

results of enforcement
After clicking Register

In the Upload folder

view the database

Database Picture Removal

My picture in the database is a path, exactly a file name, because my pictures are all in the Upload folder of the project directory, so when we take out pictures, we can write a file path prefix by ourselves first, and add the file name of the database to take out normally.

[HttpPost]
public ActionResult GetImg()
{
    using (SqlConnection conn = new SqlConnection("Data Source=DESKTOP-2HL1HGR\\SQL2014;Initial Catalog=TestDemo;Integrated Security=True"))
    {
        conn.Open();
        string sql = "SELECT FileName FROM tb_user WHERE Id=1";
        SqlCommand cmd = new SqlCommand(sql, conn);
        return Json(cmd.ExecuteScalar().ToString());
    }
}
<h2>Index2</h2>
<div id="showImg">
</div>
<script>
    $(function () {
        $.ajax({
            type: "post",
            url: "/Test/GetImg",
            dataType: "json",
            success: function (result) {
                var htmlStr = "<img src='/Upload/" + result + "'>";
                $("#showImg").empty().append(htmlStr);
            }
        })
    })
</script>

results of enforcement

Posted by pvraja on Thu, 09 May 2019 20:08:38 -0700