Pass PNG on form submit, Request URL Too long

后端 未结 2 915
一整个雨季
一整个雨季 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 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)
    

提交回复
热议问题