简体   繁体   English

如何从另一个站点加载图像并保存在我的站点中? 碰到CORS问题(我认为)

[英]How to load an image from another site and save in my site? Hitting a CORS issue (I think)

I have functionality on a web page similar to posting a url on Facebook. 我在网页上具有类似于在Facebook上发布网址的功能。 The user inputs an url and an image and description is loaded. 用户输入一个URL,然后加载图像和描述。 The user can then choose to post that image and description (all that works fine). 然后,用户可以选择发布该图像和说明(一切正常)。 When the user attempts to post the image, the behavior should be: Javascript will pick up the image src, load it to a canvas, resize it, add it to a form dynamically (along with the description), and post it. 当用户尝试发布图像时,行为应为:Javascript将拾取图像src,将其加载到画布上,调整其大小,动态地(连同描述)将其添加到表单中,然后进行发布。 The result should be the image and description is sent to my server for processing and saving. 结果应该是图像,并将说明发送到我的服务器进行处理和保存。 All this works just fine if I have a local image source. 如果我有本地图像源,那么所有这些工作都很好。 It fails if I have a remote image source. 如果我有远程图像源,它将失败。 My reasoning is I have a CORS issue, but I'm not sure how to solve it. 我的理由是我遇到了CORS问题,但不确定如何解决。 Here is the function with the error in the comments. 这是注释中有错误的函数。

function postNewsAuto() {
    var MAX_WIDTH = 400;
    var MAX_HEIGHT = 400;

    var img = document.createElement("img");

    /*
     * the src on the next line contains an image from another site
     */
    img.src = $('#auto-news-image').attr('src');

    img.onload = function() {
        var canvas = document.getElementById('canvas');
        var ctx = canvas.getContext('2d');
        ctx.drawImage(img, 0, 0);
        var width = img.width;
        var height = img.height;

        if (width > height) {
            if (width > MAX_WIDTH) {
                height *= MAX_WIDTH / width;
                width = MAX_WIDTH;
            }
        } else {
            if (height > MAX_HEIGHT) {
                width *= MAX_HEIGHT / height;
                height = MAX_HEIGHT;
            }
        }

        canvas.width = width;
        canvas.height = height;
        var ctx = canvas.getContext('2d');
        ctx.drawImage(img, 0, 0, width, height);

        /*
         * this next line fails with the error:
         * Security Error: The operation is insecure
         * presumably a CORS issue
         */
        var dataurl = canvas.toDataURL("image/jpeg");
        var blob = dataURItoBlob(dataurl);

        var fd = new FormData(document.forms[0]);
        fd.append("url", $('#auto-news-url').text());
        fd.append("description", $('#auto-news-url').attrib('href'));
        fd.append("image", blob);

        /*
         * at this point in the code I post 
         * the form via XMLHttpRequest()
         * this code also works, I removed it for brevity
         */
    };
}

I realize a simple way around this would be to store the image location rather than the image itself and then serve it up as needed. 我意识到解决此问题的一种简单方法是存储图像位置而不是图像本身,然后根据需要提供服务。 However I want to store it to avoid broken links since the remote image would be out of my control. 但是我想存储它以避免链接断开,因为远程映像将不受我的控制。 The real issue is then, how do I get an image from a remote size and save it to my server? 真正的问题是,如何从远程大小获取图像并将其保存到服务器? So putting aside all the resizing and posting (which I know how to do), at the most basic level, the question is simply, how do I make a copy of an image on my server from a remote site? 因此,撇开所有调整大小和发布(我知道该怎么做)的问题,最基本的问题是,如何从远程站点在服务器上复制映像?

One other function is referenced here, dataURItoBlob(). 这里引用了另一个函数dataURItoBlob()。 This function also works fine, but I've posted it for reference. 此功能也可以正常工作,但已将其发布以供参考。

function dataURItoBlob(dataURI) {
    'use strict';
    var byteString, mimestring;

    if (dataURI.split(',')[0].indexOf('base64') !== -1) {
        byteString = atob(dataURI.split(',')[1]);
    } else {
        byteString = decodeURI(dataURI.split(',')[1]);
    }

    mimestring = dataURI.split(',')[0].split(':')[1].split(';')[0];

    var content = new Array();
    for (var i = 0; i < byteString.length; i++) {
        content[i] = byteString.charCodeAt(i);
    }

    return new Blob([new Uint8Array(content)], {type: mimestring});
}

You have two options suitable for your case. 您有两种适合您情况的选择。

Bad solution 不好的解决方案

Setup CORS headers on remote website. 在远程网站上设置CORS标头。 However this solution is wrong for you, because you cannot control every website out there and ask them to setup CORS headers for you. 但是,该解决方案对您来说是错误的,因为您无法控制那里的每个网站,都无法要求他们为您设置CORS标头。

Good solution 好的解决方案

You need to write server proxying middleware (Python, Node, etc.) which will send request any remote website and return content. 您需要编写服务器代理中间件(Python,Node等),该中间件将向任何远程网站发送请求并返回内容。 This solution is better because your own server will not hit CORS issue. 此解决方案更好,因为您自己的服务器不会遇到CORS问题。

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

相关问题 使用javascript从另一个站点加载图像 - Using javascript to load an image from another site 如何防止网站通过图像将 cookie 放入我的网站? - How can I prevent a site from putting cookies in my site through an image? IdentitySever与SPA站点CORS问题 - IdentitySever with SPA Site CORS Issue 如何在我的网站中使用php curl将另一个网站内容加载到div中 - how to load another site content using php curl into a div in my site 如何从重定向的付款处理器站点提取交易详细信息并将其保存到我的4 db - How do I extract transaction details from a redirected Payment Processor Site and save to my rails 4 db 如何加载用于网站的外部字体? - How do I load external font to use for my site? 如何从http网站加载元素并将其添加到我的网站 - How do I load elements from a http site and add it to my website 如何从响应式 web 站点在 iPhone 上保存文件 - How do I save a file on iPhone from a responsive web site 如何通过网络服务器创建使用php作为代理的外部网站iframe? (避免CORS) - How do I create an external site iframe that uses php as proxy through my webserver? (avoiding CORS) Next.js Cors-如何从外部站点调用我的 Next js API - Next.js Cors- How to call my Next js API from the external site
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM