简体   繁体   English

如何使用FileReader API从url上传图像文件?

[英]how to upload image file from url using FileReader API?

In html form, we have a image field, to upload a file. 在html表单中,我们有一个图像字段,用于上传文件。 I followed tutorial from http://blog.teamtreehouse.com/reading-files-using-the-html5-filereader-api and it works fine when uploading a image file from local disk. 我从http://blog.teamtreehouse.com/reading-files-using-the-html5-filereader-api上学习了教程,从本地磁盘上传图像文件时效果很好。

But suppose i have a image url say http://www.google.com/images/logos/ps_logo2.png and want to upload this image from remote url instead of uploading from local disk. 但是假设我有一个图片网址,请说http://www.google.com/images/logos/ps_logo2.png并希望从远程网址上传此图片,而不是从本地磁盘上传。

FileReader API works well when trying upload image from local disk but how can we use it to load images by urls? 尝试从本地磁盘上传图像时, FileReader API运行良好,但我们如何使用它来按网址加载图像?

Its easy to create a base64 of image and use it for preview by setting in image field as <img src='data:image/png;base64,iAks4ds__base64__string' id='user_img'> but what workflow should one adopt to upload images from remote url using jQuery or JavaScript? 通过将图像字段设置为<img src='data:image/png;base64,iAks4ds__base64__string' id='user_img'>轻松创建base64图像并将其用于预览,但是应该采用哪种工作流来上传图像使用jQuery或JavaScript的远程URL?

How can i? 我怎么能够? Any suggestions? 有什么建议?

FileReader API is dedicated to local files (cf http://www.html5rocks.com/en/tutorials/file/dndfiles/ ) FileReader API专用于本地文件 (参见http://www.html5rocks.com/en/tutorials/file/dndfiles/

If you want to download an image from a remote URL and extract its data in javascript you can use Image and Canvas elements, as explained in the following question: Convert an image into binary data in javascript 如果要从远程URL下载图像并在javascript中提取其数据,可以使用ImageCanvas元素,如以下问题中所述: 在javascript中将图像转换为二进制数据

as @fiddler answer says, fileReader is for local files only, if you need to get things like images from remote urls, then you may follow another approach 正如@fiddler的回答所说, fileReader仅用于本地文件,如果你需要从远程网址获取图像,那么你可以采用另一种方法

1) using Http Get request 1) 使用Http Get请求
2) using Canvas features 2) 使用Canvas功能

but due to security threat, browsers not allow scripts to do cross origin requests, only DOM itself can do that. 但由于安全威胁,浏览器不允许脚本执行跨源请求,只有DOM本身才能这样做。 that can be solve by 这可以解决

1) Cors (Cross-Origin Resource Sharing) ? 1)Cors(跨源资源共享)
2) Jsonp ? 2)Jsonp

now you curious so cors or jsonp 现在你好奇所以cors或jsonp

if you have access to server where your remote things exist you can do server side cors ? 如果你有权访问存在远程事物的服务器,你可以做服务器端的cors 吗? , which is recommended by most. ,这是大多数人推荐的。

but as question looking for a solution which can handle any remote resources, cors proxy ? 但是作为寻找可以处理任何远程资源的解决方案的问题,cors代理 help you 帮你
free cors proxies 免费的角色代理

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

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