简体   繁体   English

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

[英]How to read image files from url using only vanilla javascript?

Is there a way to read image files from url using only vanilla javascript ?有没有办法只使用vanilla javascript从 url 读取图像文件? As context, I'm building a simple drag and drop image uploader and I think I've got the part where you read a literal file from a PC, but as for URLs how can I do it?作为上下文,我正在构建一个简单的拖放图像上传器,我想我已经掌握了从 PC 读取文字文件的部分,但至于 URL,我该怎么做呢? Example: https://imgur.com/upload示例: https ://imgur.com/upload

I would like to be able to drag an image from google and have it read in the dropzone.我希望能够从谷歌拖动图像并在拖放区中读取它。

https://codepen.io/Ryenra/pen/JjoyPaq 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'); } }
 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; }
 <.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>

You can use the Fetch API like Nigel mentioned.您可以像 Nigel 提到的那样使用Fetch API

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

fetch will return a response that you need to read as a Blob using res.blob() fetch将返回一个响应,您需要使用res.blob()将其作为Blob读取

Note: both fetch and res.blob return a promise which needs to be resolved using either .then() like in the example or async/await.注意: fetchres.blob都返回一个 promise,需要使用示例中的 .then .then()或 async/await 来解决。

Blob and File are basically the same so you can probably use the Blob for whatever you need, but if you really need to, you can convert it into a File by using the File() constructor like this: BlobFile基本相同,因此您可以根据需要使用Blob ,但如果确实需要,可以使用File() 构造函数将其转换为File ,如下所示:

let file = new File([blob], "file name", {type: blob.type})

However because CORS exists, you might run into issues when trying to fetch images from arbitrary sites.但是,由于存在CORS ,您可能会在尝试从任意站点获取图像时遇到问题。 Then you'll probably have to create a proxy server to fetch the images and add the 'Access-Control-Allow-Origin' header to the image with the value of either "*" (any domain) or "the domain your site is on".然后,您可能必须创建一个代理服务器来获取图像,并将“Access-Control-Allow-Origin”标头添加到图像中,其值为“*”(任何域)或“您的站点所在的域”在”。

Sorry for the plug, but I've recently wrote a guide on working with files on the client-side recently and it might prove useful for your project: Using Files in Client-Side JavaScript对不起,插件,但我最近写了一篇关于最近在客户端处理文件的指南,它可能对你的项目有用: Using Files in Client-Side JavaScript

In general, you can't.一般来说,你不能。 The Same-origin policy prevents browsers from reading the data from a different origin (unless CORS is used to grant permission). 同源策略防止浏览器读取来自不同源的数据(除非使用 CORS 授予权限)。

You gave https://imgur.com/upload as an example, but they don't read the image using client-side JavaScript.您以https://imgur.com/upload为例,但他们不使用客户端 JavaScript 读取图像。 The URL itself is sent to the server, then the requested from there by server-side code. URL 本身被发送到服务器,然后由服务器端代码从那里请求。

网络请求截图

Is there a way to read image files from url using only vanilla javascript ?有没有办法只使用vanilla javascript从 url 读取图像文件? As context, I'm building a simple drag and drop image uploader and I think I've got the part where you read a literal file from a PC, but as for URLs how can I do it?作为上下文,我正在构建一个简单的拖放图像上传器,我想我已经完成了从 PC 读取文字文件的部分,但是对于 URL,我该怎么做? Example: https://imgur.com/upload示例: https : //imgur.com/upload

I would like to be able to drag an image from google and have it read in the dropzone.我希望能够从谷歌拖动图像并在放置区中读取它。

https://codepen.io/Ryenra/pen/JjoyPaq 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'); } }
 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; }
 <!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>

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

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