locked
Resize image before upload RRS feed

  • Question

  • User1510859543 posted

    We have an asp.net page with multiple FileUpload controls to allow users to select files from their browser or smart device and then upload them to our website filesystem.  It has worked fine for a long time but images are getting so much larger that uploads can now take a long time. Below is a small sample of the code we use to upload and resize the image using a Resize_Image function.  What can we do to resize the image at the time the user selects the image locally so that we are not uploading extremely large files?  I assume it will involve some sort of js or jquery code to do this.

                Dim savePath As String = "c:\W_Drive\uploads\"
                Dim strFileNames As String = ""
                Dim intFilesUploaded As Integer = 0
                Dim fileName As String = ""
                Dim strFullPath As String = ""
                Dim strTime As String = Format(DateTime.Now, "yyyyMMddhhmmss")
                Dim strName As String = ""
    
                Dim fileExtOnly As String = ""
                Dim fileNameOnly As String = ""
    
                Dim img As String = String.Empty
                Dim bmpImg As Bitmap = Nothing
    
                If (FileUpload1.HasFile) Then
                    ' Get the name of the file to upload.
                    fileName = FileUpload1.FileName
                    fileExtOnly = Path.GetExtension(fileName)
                    fileNameOnly = Path.GetFileNameWithoutExtension(fileName)
                    strTime = Format(DateTime.Now, "yyyyMMddhhmmss") & "_1"
                    fileName = fileNameOnly & strTime & fileExtOnly
    
                    ' Append the name of the file to upload to the path.
                    strFullPath = savePath & fileName
    
                    ' If a file with the same name already exists in the specified path,  
                    ' the uploaded file overwrites it.
                    If FileUpload1.PostedFile.ContentLength > 800000 Then
                        bmpImg = Resize_Image(FileUpload1.PostedFile.InputStream, 2533, 1900)
                        'save the resized image stream to jpg file
                        bmpImg.Save(strFullPath, ImageFormat.Jpeg)
                        bmpImg.Dispose()
                    Else
                        FileUpload1.SaveAs(strFullPath)
                    End If
                End If
    

    Friday, February 5, 2021 8:38 PM

Answers

  • User-939850651 posted

    Hi dlchase,

    I tested the code you provided, and I found several problems.

    1. If you need to specify the upload path from the background code, then you only need to get the upload file name from the front end, and you never need to pass other parameters in the uploadPhotos function.

    <input name="imagefile[]" type="file" id="takePictureField" accept="image/*" onchange="uploadPhotos()" />

    2. Please use the correct url parameter settings, otherwise you will not be able to call the Ajax function correctly.

    url: 'uploadPhoto.aspx/uploadPhoto',

    3. Make sure that the required folder exists in the server path.

    Here is the complete code:

    <head runat="server">
        <title>Upload Photos Test</title>
        <script src="Scripts/jquery-1.10.2.min.js"></script>
        <script type="text/javascript">
        window.uploadPhotos = function(){
            // Read in file
            var file = event.target.files[0];
    
            // Ensure it's an image
            if(file.type.match(/image.*/)) {
                alert('An image file named' + file.name + ' has been loaded ');//from url=' + url);
    
                // Load the image
                var reader = new FileReader();
                reader.onload = function (readerEvent) {
                    var image = new Image();
                    image.onload = function (imageEvent) {
    
                        // Resize the image
                        var canvas = document.getElementById('thecanvas'),
                            max_size = 544,     // TODO : pull max size from a site config
                            width = image.width,
                            height = image.height;
                        if (width > height) {
                            if (width > max_size) {
                                height *= max_size / width;
                                width = max_size;
                            }
                        } else {
                            if (height > max_size) {
                                width *= max_size / height;
                                height = max_size;
                            }
                        }
                        canvas.width = width;
                        canvas.height = height;
                        canvas.getContext('2d').drawImage(image, 0, 0, width, height);
                        var dataUrl = canvas.toDataURL('image/jpeg').replace("image/jpeg", "image/octet-stream");
                        
                        var resizedImage = dataURLToBlob(dataUrl);
                        $.event.trigger({
                            type: "imageResized",
                            blob: resizedImage,
                            url: dataUrl,
                            fileName: file.name
                        });
                    }
                    image.src = readerEvent.target.result;
                }
                reader.readAsDataURL(file);
            }
        };
    
    
        /* Utility function to convert a canvas to a BLOB */
            var dataURLToBlob = function (dataURL) {
            var BASE64_MARKER = ';base64,';
            if (dataURL.indexOf(BASE64_MARKER) == -1) {
                var parts = dataURL.split(',');
                var contentType = parts[0].split(':')[1];
                var raw = parts[1];
    
                return new Blob([raw], {type: contentType});
            }
    
            var parts = dataURL.split(BASE64_MARKER);
            var contentType = parts[0].split(':')[1];
            var raw = window.atob(parts[1]);
            var rawLength = raw.length;
    
            var uInt8Array = new Uint8Array(rawLength);
    
            for (var i = 0; i < rawLength; ++i) {
                uInt8Array[i] = raw.charCodeAt(i);
            }
    
            return new Blob([uInt8Array], {type: contentType});
        }
        /* End Utility function to convert a canvas to a BLOB      */
    
    
        /* Handle image resized events */
        $(document).on("imageResized", function (event) {
            var data = new FormData($("form[id*='uploadImageForm']")[0]);
            if (event.blob && event.url) {
                data.append('image_data', event.blob);
                //alert('event.url=' + event.url);
                //alert('event.file=' + event.fileName);
                $.ajax({
                    url: 'uploadPhoto.aspx/uploadPhoto',
                    data: JSON.stringify({
                        "imageData": event.url,        // this is image data
                        "fileName": event.fileName
                    }),
                    dataType: "json",
                    contentType: "application/json; charset=utf-8",
                    type: 'POST',
                    success: function(data){
                        alert('upload success');
                    },
                    error: function(data){
                        alert('upload failed');
    
                    }
                });
            }
        });
        </script>
    </head>
    
    <body>
        <input name="imagefile[]" type="file" id="takePictureField" accept="image/*" onchange="uploadPhotos()" />
        <form id="uploadImageForm" enctype="multipart/form-data">
            <input id="name" value="#{name}" />
            <canvas width="200" height="200" id="thecanvas"></canvas>
        </form>
    </body>
    <WebMethod>
        Public Shared Function uploadPhoto(ByVal imageData As String, ByVal fileName As String) As String
            Dim serverPath As String = HttpContext.Current.Server.MapPath("~/Photos/AAScanTest/")
            imageData = imageData.Replace("data:image/octet-stream;base64,", "")
    
            Try
                File.WriteAllBytes(serverPath & fileName, Convert.FromBase64String(imageData))
    
            Catch ex As Exception
                Console.WriteLine(ex.StackTrace)
                Return "Failed"
    
            End Try
    
            Return "OK"
        End Function

    Hope this can help.

    Best regards,

    Xudong Peng

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, March 2, 2021 2:55 AM
  • User-939850651 posted

    Hi dlchase,

    {"Message":"Error during serialization or deserialization using the JSON JavaScriptSerializer. The length of the string exceeds the value set on the maxJsonLength property.

    According to the description of this error, I think the problem may be because the data length of the image converted to base64 format is too long and exceeds the limit.

    Have you tried this configuration in web.config?

    <system.web.extensions>
        <scripting>
          <webServices>
            <jsonSerialization maxJsonLength=”2147483647″></jsonSerialization>
          </webServices>
        </scripting>
      </system.web.extensions>

    Hope this can help you.

    Best regards,

    Xudong Peng

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, March 3, 2021 5:23 AM

All replies

  • User-1716253493 posted

    https://stackoverflow.com/questions/23945494/use-html5-to-resize-an-image-before-upload

    Why you enlarge the image? Mostly, resize image to reduce the size for smaller storage or fast loading?

    Friday, February 5, 2021 10:49 PM
  • User1510859543 posted

    Where do you see enlarge?

    Sunday, February 7, 2021 6:39 PM
  • User-1716253493 posted

    Apologize i have not read carefully for the ContentLength limitation

    For the resize image in client side have you try the link?

    Monday, February 8, 2021 10:52 AM
  • User1510859543 posted

    Have not had a chance to try the code from the link yet. I am hoping it will handle my situation of remote device (e.g. smartphone) and 5-6 fairly large images (4-6MB each). I am wondering what happens if 1 upload is in progress when the user selects a 2nd image as there are 5-6 fileupload controls on the page.

    Monday, February 8, 2021 3:12 PM
  • User-1716253493 posted

    AFAIK, the codes resize the image in the browser instead.

    Monday, February 8, 2021 8:55 PM
  • User1510859543 posted

    OK, I will give it a try soon on my test images.

    Monday, February 8, 2021 9:13 PM
  • User1510859543 posted

    On the code link I do not understand the onchange event structure below. What is a sample value on this?

     onchange="uploadPhotos(\'#{imageUploadUrl}\')"

    Tuesday, February 16, 2021 6:34 PM
  • User1510859543 posted

    I have created below code from the link you sent. It seems to resize the image but how do I save the resized image (in "thecanvas" control) to a virtual directory named Photos/AAScanTest?

    <head runat="server">
        <title>Upload Photos Test</title>
        <script src="Scripts/jquery-1.10.2.min.js"></script>
        <script type="text/javascript">
        window.uploadPhotos = function(url){
            // Read in file
            var file = event.target.files[0];
    
            // Ensure it's an image
            if(file.type.match(/image.*/)) {
                alert('An image file=' + file.name + ' has been loaded from url=' + url);
    
                // Load the image
                var reader = new FileReader();
                reader.onload = function (readerEvent) {
                    var image = new Image();
                    image.onload = function (imageEvent) {
    
                        // Resize the image
                        var canvas = document.getElementById('thecanvas'),
                            max_size = 544,     // TODO : pull max size from a site config
                            width = image.width,
                            height = image.height;
                        if (width > height) {
                            if (width > max_size) {
                                height *= max_size / width;
                                width = max_size;
                            }
                        } else {
                            if (height > max_size) {
                                width *= max_size / height;
                                height = max_size;
                            }
                        }
                        canvas.width = width;
                        canvas.height = height;
                        canvas.getContext('2d').drawImage(image, 0, 0, width, height);
                        var dataUrl = canvas.toDataURL('image/jpeg').replace("image/jpeg", "image/octet-stream");
                        
                        var resizedImage = dataURLToBlob(dataUrl);
                        $.event.trigger({
                            type: "imageResized",
                            blob: resizedImage,
                            url: dataUrl
                        });
                    }
                    image.src = readerEvent.target.result;
                }
                reader.readAsDataURL(file);
            }
        };
    
    
        /* Utility function to convert a canvas to a BLOB */
            var dataURLToBlob = function (dataURL) {
            var BASE64_MARKER = ';base64,';
            if (dataURL.indexOf(BASE64_MARKER) == -1) {
                var parts = dataURL.split(',');
                var contentType = parts[0].split(':')[1];
                var raw = parts[1];
    
                return new Blob([raw], {type: contentType});
            }
    
            var parts = dataURL.split(BASE64_MARKER);
            var contentType = parts[0].split(':')[1];
            var raw = window.atob(parts[1]);
            var rawLength = raw.length;
    
            var uInt8Array = new Uint8Array(rawLength);
    
            for (var i = 0; i < rawLength; ++i) {
                uInt8Array[i] = raw.charCodeAt(i);
            }
    
            return new Blob([uInt8Array], {type: contentType});
        }
        /* End Utility function to convert a canvas to a BLOB      */
    
    
        /* Handle image resized events */
        $(document).on("imageResized", function (event) {
            var data = new FormData($("form[id*='uploadImageForm']")[0]);
            if (event.blob && event.url) {
                data.append('image_data', event.blob);
                alert('event.url=' + event.url);
                $.ajax({
                    url: event.url,
                    data: data,
                    cache: false,
                    contentType: false,
                    processData: false,
                    type: 'POST',
                    success: function(data){
                        alert('upload success');
                    }
                });
            }
        });
        </script>
    </head>
    
    <body>
        <input name="imagefile[]" type="file" id="takePictureField" accept="image/*" onchange="uploadPhotos('Photos/AAScanTest/uploadtest.jpg')" />
        <form id="uploadImageForm" enctype="multipart/form-data">
            <input id="name" value="#{name}" />
            <canvas width="200" height="200" id="thecanvas"></canvas>
        </form>
    </body>

    Tuesday, February 16, 2021 9:50 PM
  • User-939850651 posted

    Hi dlchase,

    I have created below code from the link you sent. It seems to resize the image but how do I save the resized image (in "thecanvas" control) to a virtual directory named Photos/AAScanTest?

    According to these codes, I tried to test them. I found that the url parameter of the uploadPhotos() function has no practical effect. If it is the location of the file you need to upload, then you have to pass the parameter to the imageResized event.

    And if you want to upload the image to the specified location (‘’), I think you can upload the file in the Ajax call in the imageResized event:

    $.event.trigger({
                            type: "imageResized",
                            blob: resizedImage,
                            url: dataUrl,
                            savePath: url
                        });
    
    
    $(document).on("imageResized", function (event) {
            var data = new FormData($("form[id*='uploadImageForm']")[0]);
            if (event.blob && event.url) {
                data.append('image_data', event.blob);
                $.ajax({
                    url: 'yourPage/uploadPhoto',
                    type: "POST",
                    data: JSON.stringify({
                        "imageData": event.url,        // this is image data
                        "savePath": event.savePath
                    }),
                    dataType: "json",
                    contentType: "application/json; charset=utf-8",
                    success: function(data){
                        alert('upload success');
    
                    }
                });
            }
        });
    <WebMethod>
    Public Shared Function uploadPhoto(ByVal imageData As String, ByVal savePath As String) As String
        Dim serverPath As String = HttpContext.Current.Server.MapPath("~/")
        imageData = imageData.Replace("data:image/octet-stream;base64,", "")
    
        Try
            File.WriteAllBytes(serverPath & savePath, Convert.FromBase64String(imageData))
        Catch ex As Exception
            Console.WriteLine(ex.StackTrace)
            Return "Failed"
        End Try
    
        Return "OK"
    End Function

    Hope this can help you.

    Best regards,

    Xudong Peng

    Friday, February 19, 2021 6:47 AM
  • User1510859543 posted

    Thank you, I will give this a try.  Since I have to upload 5 images do I just need to have each file input control use the same onchange() event? Also, do the input controls be outside the <form> control?  It was suggested on the response that this would keep it from submitting the form.

    Friday, February 19, 2021 2:19 PM
  • User-939850651 posted

    Hi dlchase,

    Since I have to upload 5 images do I just need to have each file input control use the same onchange() event?

    You cannot be sure what kind of images the user will upload, so I think you need to resize all the images.

    Also, do the input controls be outside the <form> control?

    I think this will not affect the submission of the form, you only need to get the correct data in the form. Because it is placed outside the form, it can prevent you from getting the wrong data, so it is better to place it outside the form.

    Best regards,

    Xudong Peng

    Tuesday, February 23, 2021 8:47 AM
  • User-1716253493 posted

    AFAIK, you can set the canvas or input control with runat="server". Then you can read the properties you want from server side

    Wednesday, February 24, 2021 12:30 AM
  • User1510859543 posted

    If I am using jquery ajax then I don't need to read the form controls from server side, correct?

    Wednesday, February 24, 2021 2:52 PM
  • User-939850651 posted

    Hi dlchase,

    If I am using jquery ajax then I don't need to read the form controls from server side, correct?

    If you use ajax just to pass image data, you really don't need to read form controls from the server. But if there are other data (except images) in the form, then it will depend on your requirements.

    Even after submitting the form, you can use the name property to get the data of the corresponding control.

    Best regards,

    Xudong Peng

    Thursday, February 25, 2021 10:02 AM
  • User1510859543 posted

    Can I use the same canvas control for all of the inputs since the canvas image is uploaded immediately?

    Thursday, February 25, 2021 6:01 PM
  • User-1716253493 posted

    Read the canvas properties you want to get like this

    <canvas runat="server" id="test"></canvas>
    string urlstr = ((System.Web.UI.HtmlControls.HtmlGenericControl)test).Attributes["url"].ToString();

    Friday, February 26, 2021 12:50 AM
  • User1510859543 posted

    I tried adding your suggested code but still cannot get the image data to save and upload to a file.  The web app has a virtual folder named "Photos" and that is where I want the saved image to go.  Every time I run the code it gives me the "error" function alert message.  Below is the latest set of code I am using.

    <!DOCTYPE html>
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title>Upload Photos Test</title>
        <script src="Scripts/jquery-1.10.2.min.js"></script>
        <script type="text/javascript">
        window.uploadPhotos = function(url){
            // Read in file
            var file = event.target.files[0];
    
            // Ensure it's an image
            if(file.type.match(/image.*/)) {
                alert('An image file=' + file.name + ' has been loaded from url=' + url);
    
                // Load the image
                var reader = new FileReader();
                reader.onload = function (readerEvent) {
                    var image = new Image();
                    image.onload = function (imageEvent) {
    
                        // Resize the image
                        var canvas = document.getElementById('thecanvas'),
                            max_size = 544,     // TODO : pull max size from a site config
                            width = image.width,
                            height = image.height;
                        if (width > height) {
                            if (width > max_size) {
                                height *= max_size / width;
                                width = max_size;
                            }
                        } else {
                            if (height > max_size) {
                                width *= max_size / height;
                                height = max_size;
                            }
                        }
                        canvas.width = width;
                        canvas.height = height;
                        canvas.getContext('2d').drawImage(image, 0, 0, width, height);
                        var dataUrl = canvas.toDataURL('image/jpeg').replace("image/jpeg", "image/octet-stream");
                        
                        var resizedImage = dataURLToBlob(dataUrl);
                        $.event.trigger({
                            type: "imageResized",
                            blob: resizedImage,
                            url: dataUrl,
                            savePath: url
                        });
                    }
                    image.src = readerEvent.target.result;
                }
                reader.readAsDataURL(file);
            }
        };
    
    
        /* Utility function to convert a canvas to a BLOB */
            var dataURLToBlob = function (dataURL) {
            var BASE64_MARKER = ';base64,';
            if (dataURL.indexOf(BASE64_MARKER) == -1) {
                var parts = dataURL.split(',');
                var contentType = parts[0].split(':')[1];
                var raw = parts[1];
    
                return new Blob([raw], {type: contentType});
            }
    
            var parts = dataURL.split(BASE64_MARKER);
            var contentType = parts[0].split(':')[1];
            var raw = window.atob(parts[1]);
            var rawLength = raw.length;
    
            var uInt8Array = new Uint8Array(rawLength);
    
            for (var i = 0; i < rawLength; ++i) {
                uInt8Array[i] = raw.charCodeAt(i);
            }
    
            return new Blob([uInt8Array], {type: contentType});
        }
        /* End Utility function to convert a canvas to a BLOB      */
    
    
        /* Handle image resized events */
        $(document).on("imageResized", function (event) {
            var data = new FormData($("form[id*='uploadImageForm']")[0]);
            if (event.blob && event.url) {
                data.append('image_data', event.blob);
                alert('event.url=' + event.url);
                alert('event.savePath=' + event.savePath);
                $.ajax({
                    url: 'uploadPhoto.aspx',
                    data: JSON.stringify({
                        "imageData": event.url,        // this is image data
                        "savePath": event.savePath
                    }),
                    dataType: "json",
                    contentType: "application/json; charset=utf-8",
                    type: 'POST',
                    success: function(data){
                        alert('upload success');
                    },
                    error: function(data){
                        alert('upload failed');
    
                    }
                });
            }
        });
        </script>
    </head>
    
    <body>
        <input name="imagefile[]" type="file" id="takePictureField" accept="image/*" onchange="uploadPhotos('Photos/AAScanTest/')" />
        <form id="uploadImageForm" enctype="multipart/form-data">
            <input id="name" value="#{name}" />
            <canvas width="200" height="200" id="thecanvas"></canvas>
        </form>
    </body>
    </html>

    And below is the uploadPhoto.aspx.vb code.

    Imports System.IO
    Imports System.Web.Services
    
    Partial Class uploadPhoto
        Inherits System.Web.UI.Page
    
        <WebMethod>
        Public Shared Function uploadPhoto(ByVal imageData As String, ByVal savePath As String) As String
            Dim serverPath As String = HttpContext.Current.Server.MapPath("~/Photos/AAScanTest/")
            imageData = imageData.Replace("data:image/octet-stream;base64,", "")
    
            Try
                File.WriteAllBytes(serverPath & savePath, Convert.FromBase64String(imageData))
    
            Catch ex As Exception
                Console.WriteLine(ex.StackTrace)
                Return "Failed"
    
            End Try
    
            Return "OK"
        End Function
    End Class

    Monday, March 1, 2021 9:10 PM
  • User-939850651 posted

    Hi dlchase,

    I tested the code you provided, and I found several problems.

    1. If you need to specify the upload path from the background code, then you only need to get the upload file name from the front end, and you never need to pass other parameters in the uploadPhotos function.

    <input name="imagefile[]" type="file" id="takePictureField" accept="image/*" onchange="uploadPhotos()" />

    2. Please use the correct url parameter settings, otherwise you will not be able to call the Ajax function correctly.

    url: 'uploadPhoto.aspx/uploadPhoto',

    3. Make sure that the required folder exists in the server path.

    Here is the complete code:

    <head runat="server">
        <title>Upload Photos Test</title>
        <script src="Scripts/jquery-1.10.2.min.js"></script>
        <script type="text/javascript">
        window.uploadPhotos = function(){
            // Read in file
            var file = event.target.files[0];
    
            // Ensure it's an image
            if(file.type.match(/image.*/)) {
                alert('An image file named' + file.name + ' has been loaded ');//from url=' + url);
    
                // Load the image
                var reader = new FileReader();
                reader.onload = function (readerEvent) {
                    var image = new Image();
                    image.onload = function (imageEvent) {
    
                        // Resize the image
                        var canvas = document.getElementById('thecanvas'),
                            max_size = 544,     // TODO : pull max size from a site config
                            width = image.width,
                            height = image.height;
                        if (width > height) {
                            if (width > max_size) {
                                height *= max_size / width;
                                width = max_size;
                            }
                        } else {
                            if (height > max_size) {
                                width *= max_size / height;
                                height = max_size;
                            }
                        }
                        canvas.width = width;
                        canvas.height = height;
                        canvas.getContext('2d').drawImage(image, 0, 0, width, height);
                        var dataUrl = canvas.toDataURL('image/jpeg').replace("image/jpeg", "image/octet-stream");
                        
                        var resizedImage = dataURLToBlob(dataUrl);
                        $.event.trigger({
                            type: "imageResized",
                            blob: resizedImage,
                            url: dataUrl,
                            fileName: file.name
                        });
                    }
                    image.src = readerEvent.target.result;
                }
                reader.readAsDataURL(file);
            }
        };
    
    
        /* Utility function to convert a canvas to a BLOB */
            var dataURLToBlob = function (dataURL) {
            var BASE64_MARKER = ';base64,';
            if (dataURL.indexOf(BASE64_MARKER) == -1) {
                var parts = dataURL.split(',');
                var contentType = parts[0].split(':')[1];
                var raw = parts[1];
    
                return new Blob([raw], {type: contentType});
            }
    
            var parts = dataURL.split(BASE64_MARKER);
            var contentType = parts[0].split(':')[1];
            var raw = window.atob(parts[1]);
            var rawLength = raw.length;
    
            var uInt8Array = new Uint8Array(rawLength);
    
            for (var i = 0; i < rawLength; ++i) {
                uInt8Array[i] = raw.charCodeAt(i);
            }
    
            return new Blob([uInt8Array], {type: contentType});
        }
        /* End Utility function to convert a canvas to a BLOB      */
    
    
        /* Handle image resized events */
        $(document).on("imageResized", function (event) {
            var data = new FormData($("form[id*='uploadImageForm']")[0]);
            if (event.blob && event.url) {
                data.append('image_data', event.blob);
                //alert('event.url=' + event.url);
                //alert('event.file=' + event.fileName);
                $.ajax({
                    url: 'uploadPhoto.aspx/uploadPhoto',
                    data: JSON.stringify({
                        "imageData": event.url,        // this is image data
                        "fileName": event.fileName
                    }),
                    dataType: "json",
                    contentType: "application/json; charset=utf-8",
                    type: 'POST',
                    success: function(data){
                        alert('upload success');
                    },
                    error: function(data){
                        alert('upload failed');
    
                    }
                });
            }
        });
        </script>
    </head>
    
    <body>
        <input name="imagefile[]" type="file" id="takePictureField" accept="image/*" onchange="uploadPhotos()" />
        <form id="uploadImageForm" enctype="multipart/form-data">
            <input id="name" value="#{name}" />
            <canvas width="200" height="200" id="thecanvas"></canvas>
        </form>
    </body>
    <WebMethod>
        Public Shared Function uploadPhoto(ByVal imageData As String, ByVal fileName As String) As String
            Dim serverPath As String = HttpContext.Current.Server.MapPath("~/Photos/AAScanTest/")
            imageData = imageData.Replace("data:image/octet-stream;base64,", "")
    
            Try
                File.WriteAllBytes(serverPath & fileName, Convert.FromBase64String(imageData))
    
            Catch ex As Exception
                Console.WriteLine(ex.StackTrace)
                Return "Failed"
    
            End Try
    
            Return "OK"
        End Function

    Hope this can help.

    Best regards,

    Xudong Peng

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, March 2, 2021 2:55 AM
  • User1510859543 posted

    Mixed results. The first photo upload was successful. Then I chose a second file and it failed. Then I tried a third photo and it failed. Then the fourth photo was successful.  I am not sure how to find out what caused the error. Any ideas?  I tried writing the stack trace in catch section as shown below but did not work.

                File.WriteAllText(HttpContext.Current.Server.MapPath("~/Photos/data.txt"), ex.StackTrace)

    I modified the ajax POST error to below and now I get a message of

    {"Message":"There was an error processing the request.","StackTrace":"","ExceptionType":""}

                    error: function (req, status, error) {
                        alert(req.responseText); 
                        var lbl = document.getElementById('LblError');
                        lbl.innerHTML = req.responseText;
    

    Then I added <customErrors mode="Off" /> to web.config and now the error returns below but not sure how to fix.

    {"Message":"Error during serialization or deserialization using the JSON JavaScriptSerializer. The length of the string exceeds the value set on the maxJsonLength property.\r\nParameter name: input","StackTrace":" at System.Web.Script.Serialization.JavaScriptSerializer.Deserialize(JavaScriptSerializer serializer, String input, Type type, Int32 depthLimit)\r\n at System.Web.Script.Serialization.JavaScriptSerializer.Deserialize[T](String input)\r\n at System.Web.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContext context, WebServiceMethodData methodData)","ExceptionType":"System.ArgumentException"}

    Tuesday, March 2, 2021 2:44 PM
  • User-939850651 posted

    Hi dlchase,

    {"Message":"Error during serialization or deserialization using the JSON JavaScriptSerializer. The length of the string exceeds the value set on the maxJsonLength property.

    According to the description of this error, I think the problem may be because the data length of the image converted to base64 format is too long and exceeds the limit.

    Have you tried this configuration in web.config?

    <system.web.extensions>
        <scripting>
          <webServices>
            <jsonSerialization maxJsonLength=”2147483647″></jsonSerialization>
          </webServices>
        </scripting>
      </system.web.extensions>

    Hope this can help you.

    Best regards,

    Xudong Peng

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, March 3, 2021 5:23 AM