0

I want to upload image and display in the table after clicking add to list.

I'm inserting data on the client side in HTML Table using this:

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

but it shows only a link but i want to show the image.

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);
            });

Preview Image when Upload

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]);
    }
}

Model

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 Answers1

1

Instead of imageFile =$("#imageFile").val() try using imageFile = $('<div>').append($('#ImagePreview').clone()).html()

Karan
  • 12,059
  • 3
  • 24
  • 40
  • Perfect it's working now not passing image to controller . kindly tell me this is correct: imageFile: $(this).find('td:eq(2)').html(), ??? – Journal Trends Oct 12 '18 at 09:14
  • Karan kindly looks this code what is wrong in this ?? – Journal Trends Oct 12 '18 at 12:53
  • No. I guess You need to send base64 string from src attribute of img. You should do something like: imageFile: $(this).find('img').attr('src'), – Karan Oct 12 '18 at 14:04
  • awesome it's working. thanks but image base64 string not passing to the controller. show null value in the controller I am sharing c# code kindly review this. I debug javascript code and image file show base64 string but not passing to the controller. – Journal Trends Oct 12 '18 at 15:19
  • Where’s ajax call from you post data?? – Karan Oct 12 '18 at 15:35
  • Actually you need to change imageFile from HttpPostedFileBase to string in model. Sorry I’m replying late. I’m not available for few days. – Karan Oct 13 '18 at 14:18
  • Thanks Its working @Karan but when i remove httppostfilebase then this code not working ... string fileName = Path.GetFileNameWithoutExtension(Quot[i].imageFile.FileName); all code which is start from this line . then how to save image byte in path. – Journal Trends Oct 13 '18 at 17:15
  • Yes, it won’t work. You have to convert string to image. You can got help from these links. 1. https://www.codeproject.com/Questions/1190243/Check-base-string-image-type-using-Csharp 2. https://stackoverflow.com/questions/5400173/converting-a-base-64-string-to-an-image-and-saving-it – Karan Oct 14 '18 at 04:37