简体   繁体   English

javascript-从URL图像获取datauri(同步XMLHttpRequest blob请求)

[英]javascript - Get datauri from URL images (Synchronous XMLHttpRequest blob requests)

I'm generating a PDF document using jsPDF , however I need to add the images submitted in the form into this document. 我正在使用jsPDF生成PDF文档,但是我需要将表单中提交的图像添加到该文档中。

// You'll need to make your image into a Data URL
// Use http://dataurl.net/#dataurlmaker
var imgData = 'data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEASABIAAD/2wBDAAIBAQEBAQIBAQECAgICAgQDAgICAgUEBAMEBgUGBgYFBgYGBwkIBgcJBwYGCAsICQoKCgoKBggLDAsKDAkKCgr/2wBDAQICAgICAg[...]' //snip
[...]
doc.addImage(imgData, 'JPEG', 15, 40, 180, 160)

However, as shown in the snip above I need to convert the file to DataURI, but I haven't found a library that does this, nor a reliable way to do it with pure JavaScript. 但是,如上面的片段所示,我需要将文件转换为DataURI,但是我没有找到执行此操作的库,也没有找到使用纯JavaScript的可靠方法。

I found the following method that allows me to extract the DataURI from an URL with XMLHttpRequest. 我发现以下方法允许我使用XMLHttpRequest从URL中提取DataURI。

function obtenerDataUri(url, pos, lastpos, isleft) 
{
    var request = new XMLHttpRequest();
    request.open('GET', url, true);
    request.responseType = 'blob';
    request.onload = function() {
        var reader = new FileReader();
        reader.readAsDataURL(request.response);
        reader.onload = function(e){
            var imgData = e.target.result.replace("data:application/xml;", "data:application/png;"), pos, lastpos, isleft;
            doc.addImage(imgData, 'PNG', (isleft) ? 15 : 90, (isleft) ? pos : lastpos, 75, 75);
        };
    };
    request.send();
}

This method doesn't work for me because it's asynchronous, it means I'm adding the content in the PDF after it's fully generated. 该方法对我不起作用,因为它是异步的,这意味着我在完全生成PDF之后添加内容。 This method doesn't work synchronously because responseType is not supported in synchronous requests(probably due the deprecation). 此方法无法同步工作,因为同步请求中不支持responseType (可能是由于弃用)。

Note that these images are already uploaded to the server when the PDF is ready to be generated, so I can't get the DataURIs on local files. 请注意,当准备好生成PDF时,这些图像已经上传到服务器了,因此我无法在本地文件上获取DataURI。

This function is called from here: 该函数从这里调用:

$('#imgArea img').each(function()
{
  g_bPDFGisLeft = !g_bPDFGisLeft;
  var bPDFGposCheck = true;
    while(bPDFGposCheck)
    {
      var pos = (g_iPDFGpage == 0) ? doc.autoTable.previous.finalY+8+(75*g_iPDFGimg) : (75*g_iPDFGimg);
      if((pos+(75*(g_iPDFGimg+1))) >= 300)
      {
        doc.addPage();
        g_iPDFGimg = 0;
        g_iPDFGpage++;
        bPDFGposCheck = true;
      }
      else
        bPDFGposCheck = false;
    }

    obtenerDataUri($(this).attr('src'), pos, g_fPDFGlastPos, g_bPDFGisLeft);

    g_fPDFGlastPos = pos;
    if(!g_bPDFGisLeft)
      g_iPDFGimg++;
});

After executing obtenerDataUri , due the fact it's doing a request, won't wait until the onload function completes. 执行obtenerDataUri ,由于它正在执行请求,因此不会等到onload函数完成。 This mean the PDF generator will keep adding pages and placing the images asynchronously in the incorrect pages. 这意味着PDF生成器将继续添加页面并将图像异步放置在不正确的页面中。

How can I get the DataURI in a synchronous way from URL images? 如何从URL图像以同步方式获取DataURI?

I appreciate any help with this issue. 感谢您提供有关此问题的帮助。 Please tell me if you need more details about this. 如果您需要更多详细信息,请告诉我。

Don't return result. 不返回结果。 Instead pass it to a callback function: 而是将其传递给回调函数:

function obtenerDataUrl(url) 
{
  var request = new XMLHttpRequest();
  request.open('GET', url, true);
  request.responseType = 'blob';
  request.onload = function() {
      var reader = new FileReader();
      reader.readAsDataURL(request.response);
      reader.onload = function(e){
          //return e.target.result;
          handleResult(e.target.result);
      };
  };
  request.send();
}

function handleResult(result) {
    var imgData = result; // or take whatever you need inside result
    doc.addImage(imgData, 'JPEG', 15, 40, 180, 160);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM