Im trying to add an image uploader on my website. I have a javascript with jcrop (the scrip is not mine, I used the one I found on the Internet); this script takes image file from computer crops it and passes to php. It starts with converting the form output to javascrip file.

var oFile = $('#image_file')[0].files[0];

This is a key line for the script, everything else is derived from oFile. I want to make it avaliable for users to upload pictures by adding a weblink (i already made possible saving image files on the localhost be posting a link); How can I open the image from my localhost with javascript and put it in the same format as oFile variable in the line above, so that my script can work with it?

有帮助吗?

解决方案

You can use binary Ajax in modern browsers to fetch a resource as a file:

var oReq = new XMLHttpRequest();
oReq.open("GET", fileURLGivenByUser, true);
oReq.responseType = "blob";

oReq.onload = function(oEvent) {
  var oFile = oReq.response;
  processTheFileSomehow(oFile);
};

oReq.send();

This will work as long as either:

  • fileURLGivenByUser is on the same domain as the page running the script (e.g., your cropping script runs on foo.com and the image link is also on foo.com), or

  • A target image resource is served with the Access-Control-Allow-Origin: * CORS response header (e.g., your cropping script runs on foo.com, the image link is on bar.com, and bar.com serves the file with acceptable CORS headers)

So, for your user to use a localhost link, the user must be running a local Web server, and that Web server must serve its images with Access-Control-Allow-Origin: * or Access-Control-Allow-Origin: whateverdomainyouuse.com (i.e., whatever domain your cropping script runs on).

If the CORS restrictions are too restrictive (they likely are), you can use a server-side proxy on your host. For example, when you request

http://mydomain.com/proxy/http://targetdomain.com/image.png

the server does a request and responses with the contents of

http://targetdomain.com/image.png
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top