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();
            }
5
  • Where's $('#imageFile');? Replace that with $('[name=imageFile]') Commented Oct 12, 2018 at 8:28
  • on top you can see imageFile. Commented Oct 12, 2018 at 9:09
  • and How to show in saveQuotation function. Commented Oct 12, 2018 at 9:09
  • There's no <input id="imageFile"...> Commented Oct 12, 2018 at 10:20
  • Use URL.createObjectURL instead of using the FileReader Commented Oct 13, 2018 at 22:59

1 Answer 1

1

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

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

8 Comments

Perfect it's working now not passing image to controller . kindly tell me this is correct: imageFile: $(this).find('td:eq(2)').html(), ???
Karan kindly looks this code what is wrong in this ??
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'),
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.
Where’s ajax call from you post data??
|

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.