如何仅使用 vanilla javascript 从 url 读取图像文件?

Rye*_*nra 6 html javascript

有没有一种方法可以仅使用vanilla javascript从 url 读取图像文件?作为上下文,我正在构建一个简单的拖放图像上传器,我想我已经有了从 PC 读取文字文件的部分,但至于 URL,我该怎么做呢?示例: https: //imgur.com/upload

我希望能够从谷歌拖动图像并在拖放区中读取它。

https://codepen.io/Ryenra/pen/JjoyPaq

function dropEv(e) {
    e.preventDefault();
    e.stopPropagation();
}

function dragOver(e) {
    document.getElementById('box').style = "opacity: 0.9;";
}

function dragLeave(e) {
    document.getElementById('box').style.removeProperty('opacity');
}


function receiveFile(e) {    
    let temp = e.dataTransfer.files;
    if(temp.length && temp[0].type.match(/image.*/)){
        document.getElementById('eText').textContent = temp[0].name;
    }else{
        alert('nv');
    }
}
Run Code Online (Sandbox Code Playgroud)
html,body{
    height: 100%    
}

#content {
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
}


#box{
    width: 350px;
    height: 300px;   
    background: repeating-linear-gradient(
  -55deg,
  #222,
  #222 10px,
  #333 10px,
  #333 20px
);
    display: flex;
    justify-content: center;
    align-items: center;
}

#opa{
    width: 100%;
    height: 100%;
    border: 2px solid #000;
    display: flex;
    justify-content: center;
    align-items: center;
}



#inputFile{
    display: none;
}
Run Code Online (Sandbox Code Playgroud)
<!DOCTYPE html>
<html lang="en">
<head>
    <link rel="stylesheet" href="style.css">
    <script src="script.js"></script>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <div id="content">           
            <div id="box" ondrop="dropEv(event),dragLeave(event),receiveFile(event)"  ondragover="dragOver(event),dropEv(event)" ondragleave="dragLeave(event)">
                <div id= "opa">
                        <p id="eText">Choose an image or drag it here!</p>
                </div>   
            </div>                  
    </div>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

小智 1

您可以像 Nigel 提到的那样使用Fetch API

fetch('the image url', {mode: 'cors'})
  .then(res => res.blob())
  .then(blob => { /* use the blob */ })
Run Code Online (Sandbox Code Playgroud)

fetch将返回一个响应,您需要Blob使用res.blob()来读取该响应

注意:fetchres.blob返回一个需要使用.then()示例中或 async/await 来解决的承诺。

BlobFile基本上是相同的,因此您可以使用 aBlob来满足您的需要,但如果您确实需要,您可以File使用File() 构造函数将其转换为 a ,如下所示:

let file = new File([blob], "file name", {type: blob.type})
Run Code Online (Sandbox Code Playgroud)

但是,由于CORS的存在,您在尝试从任意站点获取图像时可能会遇到问题。然后,您可能需要创建一个代理服务器来获取图像,并将“Access-Control-Allow-Origin”标头添加到图像中,其值为“*”(任何域)或“您网站所在的域”在”。

抱歉这个插件,但我最近写了一篇关于在客户端处理文件的指南,它可能对您的项目有用:在客户端 JavaScript 中使用文件