在 Javascript 中将图像 (jpg) 转换为 Base64 格式时出现问题

发布于 2024-11-08 07:00:07 字数 6425 浏览 4 评论 0原文

我需要从本地硬盘读取图像文件并将其转换为 Base64 格式。转换后,我需要将 base64 字符串传递给 Web 服务并从 Web 服务获取结果。

我有一个相同的代码:

<html>

<script>
// create the object

//test = new Base64();

x = new XMLHttpRequest();

// set the function that should be called when
// the ready state changes (the callback)
x.onreadystatechange = handleDoc;
// establish the method and URL
//x.open('GET', "Latest Eticket.jpg", true);
x.overrideMimeType("text/plain; charset=x-user-defined");
x.open('GET', 'file:///C:\\vishwa\\Node_JS\\Jquery_ajax\\JS_with_Ajax\\base64_encode\\Latest Eticket.jpg', true);
//x.open('GET', 'C:\vishwa\Node_JS\Jquery_ajax\JS_with_Ajax\base64_encode\Latest Eticket.jpg', true);
//x.open('GET', 'http://www.google.co.in/imgres?imgurl=http://1.bp.blogspot.com/_PveGYAt2T10/TDRH1kJsXAI/AAAAAAAAAgI/a45pNA5hxrA/s1600/hi-pig.jpg&imgrefurl=http://weiwei95.blogspot.com/2010_07_01_archive.html&usg=__k761BPCJk7FGxAgy8UHUiCCO1dA=&h=474&w=600&sz=51&hl=en&start=1&sig2=K2Z27chXr6EPO-lHJVY43g&zoom=1&tbnid=NSx-UedGEdm84M:&tbnh=107&tbnw=135&ei=uezUTbaDFMSBgAet_7iVDA&prev=/search%3Fq%3Dhi%26hl%3Den%26biw%3D1024%26bih%3D548%26gbv%3D2%26tbm%3Disch&itbs=1', true);
//x.open('GET', 'http://localhost:80//Latest Eticket.jpg', true);
// initiate the HTTP transaction
x.send(null);


//
function handleDoc() {
//window.alert("READY STATE IS " +
//x.readyState);
if(x.readyState == 1)
{
    window.alert("Handling x 1 State: The response is started");
}
if(x.readyState == 4)
{
    var encodeImagescanned_image = '';
    alert("Am i coming here 4-2"+x.responseText);
                    //var base64 = new Base64();
                    encodeImagescanned_image = encode(x.responseText);
                    alert("Am i coming here 4-3"+encodeImagescanned_image);
    window.alert("Handling x 4 State: The response is ended");

    alert("Constructing Soap body");
    var xmlp = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:dsf=\"http://DSFService/\">" +
                    "<soapenv:Header/>" +
                    "<soapenv:Body>" +
                    "<dsf:FieldExtraction>" +
                    "<dsf:inImage>" +
                    this.encodeImagescanned_image +
                    "</dsf:inImage>" +
                    "</dsf:FieldExtraction>" +
                    "</soapenv:Body>" +
                    "</soapenv:Envelope>";
                    var xmlps = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:dsf=\"http://DSFService/\">" +
                    "<soapenv:Header/>" +
                    "<soapenv:Body>" +
                    "<dsf:FieldExtraction>" +
                    "<dsf:inImage>" +
                    "</dsf:inImage>" +
                    "</dsf:FieldExtraction>" +
                    "</soapenv:Body>" +
                    "</soapenv:Envelope>";

                    var dsfUrl = "http://hpldsf-tst.asiapacific.cpqcorp.net:8090/DSFServiceSite/DSFService.svc/basic";
                    request = new XMLHttpRequest();
                        // We're going to be POSTing to this URL and want a synchronous response
                    request.open("POST", dsfUrl, true);
                    request.setRequestHeader("Content-Type", "text/xml;charset=UTF-8");
                    request.setRequestHeader("Content-length", xmlp.length);
                    request.setRequestHeader("Accept-Encoding", "gzip,deflate");
                    request.timeout = 300000;
                    // This header is a required part of the SOAP protocol
                    request.setRequestHeader("SOAPAction", '\"http://DSFService/DSFService/FieldExtraction\"');
                    // Now send an XML-formatted SOAP request to the server
                    request.send(xmlp);
                    request.onreadystatechange = handlesoap;


}
}

function handlesoap()
{
    alert("Inside handlesoap function");
    if(request.readyState == 4)
    {
        var xmls = request.responseText;
        var xmlDoc = (new DOMParser()).parseFromString(xmls, "text/xml");
        var doc = xmlDoc.documentElement;
        var nvalue = xmlDoc.getElementsByTagName('FieldExtractionResponse')[0];
        alert("nvalu ="+nvalue);
        if ((nvalue !== null) && (nvalue !== undefined)) 
        {

            ////var docidval = nodes.getAttribute("id");
            ///Mojo.Log.info("docidval:" + docidval);
            dsfxml = xmls; //nodes.nodeValue;
            var pattern = /\cM/;

                                // Break the string into pieces separated by the pattern above and
                                // and store the pieces in an array called nameList
                                var nameList = [];
                                nameList = dsfxml.split(pattern);
                                var clean = '';
                                for (i = 0; i < nameList.length; i++) {

                                    clean = clean + nameList[i].replace(pattern, "").trim();
                                }
        }
        else
        {
            alert("nvalue is eitheer null or undefined");
        }
    }
}



    function encode(input) {
    alert("I am in encode function");
    var _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
    var output = "";
    var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
    var i = 0;

    while (i < input.length) {
        chr1 = input.charCodeAt(i++) & 0xff; //alert('chr1 : ' + chr1.toString(16));
        chr2 = input.charCodeAt(i++) & 0xff; //alert('chr2 : ' + chr2.toString(16));
        chr3 = input.charCodeAt(i++) & 0xff; //alert('chr3 : ' + chr3.toString(16));

        enc1 = chr1 >> 2;
        enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
        enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
        enc4 = chr3 & 63;

        if (isNaN(chr2)) {
        enc3 = enc4 = 64;
        } else if (isNaN(chr3)) {
        enc4 = 64;
        }

        output = output +
        _keyStr.charAt(enc1) + _keyStr.charAt(enc2) +
        _keyStr.charAt(enc3) + _keyStr.charAt(enc4);

    }

    return output;
}

</script>
</html>

问题是它没有将图像正确转换为 base64 格式。你能帮我知道我错在哪里吗......

I need to read an image file from the local hard drive and convert the same to base64 format. After conversion i need to pass the base64 string to a webservice and get the result from a webservice.

I have a code for the same:

<html>

<script>
// create the object

//test = new Base64();

x = new XMLHttpRequest();

// set the function that should be called when
// the ready state changes (the callback)
x.onreadystatechange = handleDoc;
// establish the method and URL
//x.open('GET', "Latest Eticket.jpg", true);
x.overrideMimeType("text/plain; charset=x-user-defined");
x.open('GET', 'file:///C:\\vishwa\\Node_JS\\Jquery_ajax\\JS_with_Ajax\\base64_encode\\Latest Eticket.jpg', true);
//x.open('GET', 'C:\vishwa\Node_JS\Jquery_ajax\JS_with_Ajax\base64_encode\Latest Eticket.jpg', true);
//x.open('GET', 'http://www.google.co.in/imgres?imgurl=http://1.bp.blogspot.com/_PveGYAt2T10/TDRH1kJsXAI/AAAAAAAAAgI/a45pNA5hxrA/s1600/hi-pig.jpg&imgrefurl=http://weiwei95.blogspot.com/2010_07_01_archive.html&usg=__k761BPCJk7FGxAgy8UHUiCCO1dA=&h=474&w=600&sz=51&hl=en&start=1&sig2=K2Z27chXr6EPO-lHJVY43g&zoom=1&tbnid=NSx-UedGEdm84M:&tbnh=107&tbnw=135&ei=uezUTbaDFMSBgAet_7iVDA&prev=/search%3Fq%3Dhi%26hl%3Den%26biw%3D1024%26bih%3D548%26gbv%3D2%26tbm%3Disch&itbs=1', true);
//x.open('GET', 'http://localhost:80//Latest Eticket.jpg', true);
// initiate the HTTP transaction
x.send(null);


//
function handleDoc() {
//window.alert("READY STATE IS " +
//x.readyState);
if(x.readyState == 1)
{
    window.alert("Handling x 1 State: The response is started");
}
if(x.readyState == 4)
{
    var encodeImagescanned_image = '';
    alert("Am i coming here 4-2"+x.responseText);
                    //var base64 = new Base64();
                    encodeImagescanned_image = encode(x.responseText);
                    alert("Am i coming here 4-3"+encodeImagescanned_image);
    window.alert("Handling x 4 State: The response is ended");

    alert("Constructing Soap body");
    var xmlp = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:dsf=\"http://DSFService/\">" +
                    "<soapenv:Header/>" +
                    "<soapenv:Body>" +
                    "<dsf:FieldExtraction>" +
                    "<dsf:inImage>" +
                    this.encodeImagescanned_image +
                    "</dsf:inImage>" +
                    "</dsf:FieldExtraction>" +
                    "</soapenv:Body>" +
                    "</soapenv:Envelope>";
                    var xmlps = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:dsf=\"http://DSFService/\">" +
                    "<soapenv:Header/>" +
                    "<soapenv:Body>" +
                    "<dsf:FieldExtraction>" +
                    "<dsf:inImage>" +
                    "</dsf:inImage>" +
                    "</dsf:FieldExtraction>" +
                    "</soapenv:Body>" +
                    "</soapenv:Envelope>";

                    var dsfUrl = "http://hpldsf-tst.asiapacific.cpqcorp.net:8090/DSFServiceSite/DSFService.svc/basic";
                    request = new XMLHttpRequest();
                        // We're going to be POSTing to this URL and want a synchronous response
                    request.open("POST", dsfUrl, true);
                    request.setRequestHeader("Content-Type", "text/xml;charset=UTF-8");
                    request.setRequestHeader("Content-length", xmlp.length);
                    request.setRequestHeader("Accept-Encoding", "gzip,deflate");
                    request.timeout = 300000;
                    // This header is a required part of the SOAP protocol
                    request.setRequestHeader("SOAPAction", '\"http://DSFService/DSFService/FieldExtraction\"');
                    // Now send an XML-formatted SOAP request to the server
                    request.send(xmlp);
                    request.onreadystatechange = handlesoap;


}
}

function handlesoap()
{
    alert("Inside handlesoap function");
    if(request.readyState == 4)
    {
        var xmls = request.responseText;
        var xmlDoc = (new DOMParser()).parseFromString(xmls, "text/xml");
        var doc = xmlDoc.documentElement;
        var nvalue = xmlDoc.getElementsByTagName('FieldExtractionResponse')[0];
        alert("nvalu ="+nvalue);
        if ((nvalue !== null) && (nvalue !== undefined)) 
        {

            ////var docidval = nodes.getAttribute("id");
            ///Mojo.Log.info("docidval:" + docidval);
            dsfxml = xmls; //nodes.nodeValue;
            var pattern = /\cM/;

                                // Break the string into pieces separated by the pattern above and
                                // and store the pieces in an array called nameList
                                var nameList = [];
                                nameList = dsfxml.split(pattern);
                                var clean = '';
                                for (i = 0; i < nameList.length; i++) {

                                    clean = clean + nameList[i].replace(pattern, "").trim();
                                }
        }
        else
        {
            alert("nvalue is eitheer null or undefined");
        }
    }
}



    function encode(input) {
    alert("I am in encode function");
    var _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
    var output = "";
    var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
    var i = 0;

    while (i < input.length) {
        chr1 = input.charCodeAt(i++) & 0xff; //alert('chr1 : ' + chr1.toString(16));
        chr2 = input.charCodeAt(i++) & 0xff; //alert('chr2 : ' + chr2.toString(16));
        chr3 = input.charCodeAt(i++) & 0xff; //alert('chr3 : ' + chr3.toString(16));

        enc1 = chr1 >> 2;
        enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
        enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
        enc4 = chr3 & 63;

        if (isNaN(chr2)) {
        enc3 = enc4 = 64;
        } else if (isNaN(chr3)) {
        enc4 = 64;
        }

        output = output +
        _keyStr.charAt(enc1) + _keyStr.charAt(enc2) +
        _keyStr.charAt(enc3) + _keyStr.charAt(enc4);

    }

    return output;
}

</script>
</html>

The problem is its not converting the image properly to base64 format. Can you please help me know where I am going wrong....

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

自我难过 2024-11-15 07:00:07

它是基于浏览器的吗?如果是这样,那么你就错了。如果您需要从本地硬盘驱动器进行复制,则包含 JavaScript 的页面将无法以字节级别访问硬盘驱动器上的任何内容。最好的情况是,您可以提供上传链接,并使用“multipart/form-data”编码类型将表单发布到服务器。

问题是...如果您的 Web 服务无法按原样理解表单发布,您可以考虑创建一个代理来接受标准表单提交,然后通过您的(urk)SOAP 请求传递它。请注意,这将是一个服务器 API,而不是客户端 API。

流程(如果需要代理):

1)。用户导航到网页。

2)。用户添加图像。

3)。用户单击“提交”

4)。文件传输至代理

5)。代理发起soap请求。

6).代理将 SOAP 请求的结果返回给客户端。

It this browser-based? If so, you're going about this wrong. If you need to copy from the local hard drive, the page containing your javascript will not be able to access anything on your hard drive at a byte level. At best, you can provide an upload link, and post your form to the server using something like a 'multipart/form-data' encoding type.

Here's the catch... If your Web service can't understand a form post as is, you may consider creating a proxy to accept the standard form submission, then pass it along through your (urk) SOAP request. Note that this would be a server API, not a client-side one.

Flow (if needing a proxy):

1). User navigates to Web page.

2). User adds image.

3). User clicks Submit

4). File is transferred to proxy

5). Proxy initiates soap request.

6). Proxy returns results of SOAP request to client.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文