2012-12-23 26 views
1

我有一個窗體,用戶可以粘貼圖像的外部網址。是否有可能通過JavaScript來抓取該文件,然後將其發佈到REST API?我爲其餘的api使用parse.com。是否可以獲取外部圖像並僅通過Javascript通過REST API發送?

+0

爲什麼你要客戶端下載文件? –

+0

那麼,我不完全確定我在做什麼。該應用程序是所有客戶端(backbone.js + parse.com)。我已經有一個上傳器工作,所以我想如果我能以某種方式獲得客戶端文件,那麼我可以像我現在一樣上傳到parse.com。 – brianandrich

+1

您可以使用'javascript'從'url'中獲取圖像[像這樣](http://jsfiddle.net/ZF3qe/1/)。 –

回答

1

無論如何,由於使用跨源資源的限制,圖像首先必須拉到服務器上。一旦你做到了這一點,你可以用我詳細的例子,將圖像轉換爲Base64,然後進入一個JSON字符串準備通過POST被運送到您的REST服務器:

<input id="urlText" /> 
<input id="sendData" type="submit" /> 
<img id="img" src="http://fiddle.jshell.net/img/logo.png" /> 
<script> 
var imgElem = document.getElementById('img'); 
$('#urlText').keyup(function(){ 
    $('#img').attr('src',$('#urlText').val()); 
}); 

$('#sendData').click(function(){ 
var imgData = JSON.stringify(getBase64Image(imgElem)); 
    $.ajax({ 
    url: 'http://url.com/rest/api', 
    dataType: 'json', 
    data: imgData, 
    type: 'POST', 
    success: function(data) { 
    console.log(data); 
    } 
    }); 
}); 

function getBase64Image(imgElem) { 
// imgElem must be on the same server otherwise a cross-origin error will be thrown "SECURITY_ERR: DOM Exception 18" 
    var canvas = document.createElement("canvas"); 
    canvas.width = imgElem.clientWidth; 
    canvas.height = imgElem.clientHeight; 
    var ctx = canvas.getContext("2d"); 
    ctx.drawImage(imgElem, 0, 0); 
    var dataURL = canvas.toDataURL("image/png"); 
    return dataURL.replace(/^data:image\/(png|jpg);base64,/, ""); 
} 
</script> 

jsFiddle example在這裏。

2

...圖像的外部網址。是否有可能通過javascript去抓取該文件...

不會,這是由same origin policy阻止,您將不被允許訪問它。只需將它的URL發佈到REST API並在服務器端獲取即可。

儘管無法訪問與其關聯的文件或數據,當然,您也可以通過嵌入<img>元素來顯示它。