0

I have an asp.net web application that shows photos from various sets. The files are on server and file locations stored in SQL database. I use the following code for getting the first image:

System.Drawing.Image img = System.Drawing.Image.FromFile(fileLocation);
string imageName = "~/Images/hw.jpg";
string savePath = Server.MapPath(@"Images\hw.jpg");
img.Save(savePath, System.Drawing.Imaging.ImageFormat.Jpeg);
img_peq_main.ImageUrl = imageName;

What I want is to retrieve the file name from the database using ajax. But the above code does not work on server-side with ajax request. How can I save the file to the Images folder and bind that source to asp. Image control? Is there any more basic way to do this?

Appreciate for help.

Ashkan Mobayen Khiabani
  • 33,575
  • 33
  • 102
  • 171
Sertan Pekel
  • 593
  • 2
  • 5
  • 23

1 Answers1

0

I solved it using MemoryStream and base64 string. Here is the code.

            System.Drawing.Image img = System.Drawing.Image.FromFile(fileLocation);
            MemoryStream ms = new MemoryStream();

            if (picType == ".jpg")
            {
                img.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
            }
            else if (picType == ".png")
            {
                img.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
            }

            string imgUrl = Convert.ToBase64String(ms.ToArray(), 0, ms.ToArray().Length);
            ms.Close();
            ms.Flush();
            //returns imgUrl to Json

Here is the Json Code. PLoc value is the returned base64 string and PType is returned Picture Type string from ajax request.

$.ajax({
            url: '/PicEq.aspx/GetNextPic',
            method: 'post',
            contentType: 'application/json',
            data: '{r_id:' + pId + '}',
            dataType: 'json',
            success: function (data) {
                var rawData = data.d.PLoc;
                if (data.d.PType == ".jpg") {
                    $('#<%=img_peq_main.ClientID%>').attr("src", "data:image/jpeg;base64," + rawData);
                }
                else if (data.d.PType == ".png") {
                    $('#<%=img_peq_main.ClientID%>').attr("src", "data:image/png;base64," + rawData);
                }
            },
            error: function (error) {
                alert(error);
            }
        });

Note that, when I first run the code, I got error on large sized files. I solved problem with this post: Can I set an unlimited length for maxJsonLength in web.config?

Thanks a lot to this great family.

Sertan Pekel
  • 593
  • 2
  • 5
  • 23
  • You can also see this for more info about asp.net streaming -> https://stackoverflow.com/questions/48646088/asp-net-core-streaming-write-chunks-to-a-request – panoskarajohn Dec 14 '19 at 12:19