如何使用jQuery在客户端的HTML表中显示图像

时间:2018-10-12 08:04:46

标签: javascript c# jquery

我要上传图像并单击添加到列表后显示在表格中。

我正在使用以下方法在HTML表的客户端插入数据:

imageFile =$("#imageFile").val()

但是它只显示一个链接,但我想显示图像。

jQuery

 $("#addToList").click(function (e) {
            e.preventDefault();
            var Srno = document.getElementById("detailsTable").rows.length,

            imageFile =$("#imageFile").val()

            detailsTableBody = $("#detailsTable tbody");
            var Qt = '<tr><td>' + Srno + '</td><td>' + imageFile + '</td><td><a 
            data-itemId="0" href="#" class="deleteItem">Remove</a></td></tr>';
            detailsTableBody.append(Qt);
            clearItem();
    });

Save Function
 $("#saveQuotation").click(function (e) {
            e.preventDefault();
            var QuotationArr = [];
            QuotationArr.length = 0;

            $.each($("#detailsTable tbody tr"), function () {

                QuotationArr.push({
                    Srno: $(this).find('td:eq(0)').html(),
                   imageFile: $(this).find('td:eq(2)').html(),

                });
            });


    function saveQuotation(data) {

                return $.ajax({
                    contentType: 'application/json; charset=utf-8',
                    dataType: 'json',
                    type: 'POST',
                    url: "/Home/mQuotationInsert",
                    data: data,
                    success: function (result) {
                        alert(result);
                        location.reload();
                    },
                    error: function () {
                        alert("Error!")
                    }
                });

            }

              var data = JSON.stringify({
                Quot: QuotationArr
                AddNew: $("#AddNew").val()
            });

            $.when(saveQuotation(data)).then(function (response) {
                console.log(response);
            }).fail(function (err) {
                console.log(err);
            });

上传时预览图像

function ShowImagePreview(ImageUploder, previewImage)
{
    if (ImageUploder.files && ImageUploder.files[0])
    {
        var reader = new FileReader();
        reader.onload = function (e) {
            $(previewImage).attr('src', e.target.result);
        }
        reader.readAsDataURL(ImageUploder.files[0]);
    }
}

型号

public string imagePath { get; set; }
[NotMapped]
public HttpPostedFileBase imageFile { get;set; }

HTML

<div class="col">

   <label for="lblPartyName">Image File</label>
    <div class="row">
      <div class="col-4">
        <input type="file" name="imageFile" accept="image/jpeg, image/png" onchange="ShowImagePreview(this,document.getElementById('ImagePreview'))" />
       </div>
        <div class="col-4" style="margin-left:30%; ">
         <img alt="image" src="~/AppFiles/Images/Default.png" height="50" width="50" style="margin-top:-15%" id="ImagePreview">
        </div>
      </div>
</div>

c#

[HttpPost]
        public ActionResult mQuotationInsert(Quotation[] Quot, string AddNew)
        {
            string result = "Error! Order Is Not Complete!";
            try
            {
                objQuotation.QuotationInsert(Quot, AddNew);
                ModelState.Clear();
                result = "Quotation Inserted Successfully!";
                return Json(result, JsonRequestBehavior.AllowGet);
            }
            catch (Exception)
            {

                throw;
            }

        }


   public int QuotationInsert(Quotation[] Quot, string AddNew)
        {
            try
            {
                con.Open();
                tr = con.BeginTransaction();
                if(Quot !=null)
                {
                    for (int i = 0; i < Quot.Length; i++)
                    {
                        try
                        {

                            string fileName = Path.GetFileNameWithoutExtension(Quot[i].imageFile.FileName);
                            string extension = Path.GetExtension(Quot[i].imageFile.FileName);
                            fileName = fileName + DateTime.Now.ToString("dd/MM/yyyy") + extension;
                            Quot[i].imagePath = "~/AppFiles/Images/" + fileName;
                            fileName = Path.Combine(HttpContext.Current.Server.MapPath("~/AppFiles/Images/"), fileName);
                            Quot[i].imageFile.SaveAs(fileName);

                   cmd = new SqlCommand("Sp_QuotationDetailInsert", con);
                    cmd.CommandType = CommandType.StoredProcedure;

                            if (Quot[i].imagePath != null)
                                cmd.Parameters.AddWithValue("@Image",fileName);

                            cmd.Transaction = tr;
                            cmd.ExecuteNonQuery();
                        }
                        catch (Exception)
                        {

                            throw;
                        }
                    }
                }

                tr.Commit();
                return i;
            }
            catch (SqlException sqlex)
            {
                tr.Rollback();
                throw sqlex;  // read all sql error 
            }
            catch (Exception ex)
            {
                tr.Rollback();
                throw ex; // General execption

            }
            finally
            {
                con.Close();
            }

1 个答案:

答案 0 :(得分:1)

尝试使用imageFile =$("#imageFile").val()代替imageFile = $('<div>').append($('#ImagePreview').clone()).html()