简体   繁体   中英

How to transform an image URL into a DOM file object using javascript/ajax?

I have a script which allows me to crop images using jcrop. To achieve that, I have to upload an image from my computer using the input type file . I want to extend the functionalities of my application, allowing the users to select photos from their facebook albuns, this code is working, but it returns me the URL of the image. From the URL I create an image object like this

var oImage = document.getElementById('preview');

But this is an image object and not a file object which will not allow me to get some file proprieties like oImage.size and oImage.type . The original code is this

<input type="file" name="image_file" id="image_file" onchange="fileSelectHandler()" />

And the javascript code

function fileSelectHandler() {
   var oFile = $('#image_file')[0].files[0];
   ...
}

Now I have a function which the callback is a Facebook image URL, and I want it to work just like if I had uploaded the image from my computer, because this input type file gets submited to server.

var oImage = document.getElementById('preview');
oImage.src = photo.source;

Where photo.source is my URL.

So my question is: How to convert a URL to a file type using javascript/ajax? I need to put that type into a file input as well because this is a form that is going to be submited. Thanks in advance.

You should post the URL to your server, then you can download the remote image with PHP and manipulat it.

Hint code:

if(isset($_POST['image_url'])){
    //Make sure to validate $_POST['image_url'] before using it
    $image = file_get_contents($_POST['image_url']);
} else {
    $image = file_get_contents($_FILES["file"]["tmp_name"]);
}

I usually use JQuery, JQuery sample ajax post:

$.post('server.php', {image_url:photo.source}, function(data){
  //do stuff on server response
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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