Pass PNG on form submit, Request URL Too long

后端 未结 2 913
一整个雨季
一整个雨季 2021-01-15 21:51

So I have an interesting question. I have a form where a user draws an image on a canvas (think a signature pad). I then need to send the image to my C# Controller (I am usi

相关标签:
2条回答
  • 2021-01-15 21:55

    Maybe you just need to increase allowed GET request URL length.

    If that doesn't works I have an aspx WebForm that saves a signature, and I use a WebMethod

    [ScriptMethod, WebMethod]
    public static string saveSignature(string data)
    {
        /*..Code..*/
    }
    

    and I call it like this:

    PageMethods.saveSignature(document.getElementById('canvas').toDataURL(), onSucess, onError);
    

    also I have to increase the length of the JSON request and it works fine, with no problems with the lenght.

    In MVC there isn't WebMethods, but JSON and AJAX requests do the job, just save the data in a session variable, and then use it when need it.

    Hope it helps

    0 讨论(0)
  • 2021-01-15 22:12

    You have error because your data is string (base64) and have max limit for send characters, better way is to create blob (png file) from base64 at client side, and send it to server. Edit. All listed code here, exists in stackoverflow posts.

    function dataURItoBlob(dataURI) {
        // convert base64 to raw binary data held in a string
        // doesn't handle URLEncoded DataURIs - see SO answer #6850276 for code that does this
        var byteString = atob(dataURI.split(',')[1]);
    
        // separate out the mime component
        var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0]
    
        // write the bytes of the string to an ArrayBuffer
        var ab = new ArrayBuffer(byteString.length);
        var ia = new Uint8Array(ab);
        for (var i = 0; i < byteString.length; i++) {
            ia[i] = byteString.charCodeAt(i);
        }
        var blob = null;
        // TypeError old chrome and FF
        window.BlobBuilder = window.BlobBuilder || 
                             window.WebKitBlobBuilder || 
                             window.MozBlobBuilder || 
                             window.MSBlobBuilder;
        if(window.BlobBuilder){
             var bb = new BlobBuilder();
             bb.append(ab);
             blob = bb.getBlob(mimeString);
        }else{
             blob = new Blob([ab], {type : mimeString});
        }
        return blob;
    }
    
    function sendFileToServer(file, url, onFileSendComplete){
       var formData = new FormData()
       formData.append("file",file); 
       var xhr = new XMLHttpRequest();
       xhr.open('POST', url, true);
       xhr.onload = onFileSendComplete;
       xhr.send(formData);
    }
    
    var base64 = $('#signature').jSignature("getData");
    var blob = dataURItoBlob(base64);
    var onComplete = function(){alert("file loaded to server");}
    sendFileToServer(blob, "/server", onComplete)
    
    0 讨论(0)
提交回复
热议问题