2012-03-06 31 views
0

我試圖使用JavaScript來上傳圖片由this example到imgur Imgur API獲取URL:從使用JavaScript

<!DOCTYPE html><meta charset="utf8"><title>Yo.</title> 
<div>DROP!<button onclick="document.querySelector('input').click()">Or click</button></div> 
<input style="visibility: collapse; width: 0px;" type="file" onchange="upload(this.files[0])"> 
<script> 
/* Drag'n drop stuff */ 
window.ondragover = function(e) {e.preventDefault()} 
window.ondrop = function(e) {e.preventDefault(); upload(e.dataTransfer.files[0]); } 
function upload(file) { 

    /* Is the file an image? */ 
    if (!file || !file.type.match(/image.*/)) return; 

    /* It is! */ 
    document.body.className = "uploading"; 

    /* Lets build a FormData object*/ 
    var fd = new FormData(); // I wrote about it: https://hacks.mozilla.org/2011/01/how-to-develop-a-html5-image-uploader/ 
    fd.append("image", file); // Append the file 
    fd.append("key", "6528448c258cff474ca9701c5bab6927"); // Get your own key http://api.imgur.com/ 
    var xhr = new XMLHttpRequest(); // Create the XHR (Cross-Domain XHR FTW!!!) Thank you sooooo much imgur.com 
    xhr.open("POST", "http://api.imgur.com/2/upload.json"); // Boooom! 
    xhr.onload = function() { 
     // Big win! 
     document.querySelector("#link").href = JSON.parse(xhr.responseText).upload.links.imgur_page; 
     document.body.className = "uploaded"; 
    } 
    // Ok, I don't handle the errors. An exercice for the reader. 

    /* And now, we send the formdata */ 
    xhr.send(fd); 
} 
</script> 

<!-- Bla bla bla stuff ... --> 

<style> 
body {text-align: center; padding-top: 100px;} 
div { border: 10px solid black; text-align: center; line-height: 100px; width: 200px; margin: auto; font-size: 40px; display: inline-block;} 
#link, p , div {display: none} 
div {display: inline-block;} 
.uploading div {display: none} 
.uploaded div {display: none} 
.uploading p {display: inline} 
.uploaded #link {display: inline} 
em {position: absolute; bottom: 0; right: 0} 
</style> 

<p>Uploading...</p> 
<a id="link">It's online!!!</a> 

這個例子把圖片網址鏈接,喜歡文字「這是網上!」

你能幫我上傳後如何得到圖片的網址嗎?我希望顯示圖像URL(例如,用URL替換「It's online !!!」),而不是放在鏈接中。

回答

2

而不是將設置#鏈接的href值,設置其值innerHTML值。或者其他元素的值爲innerHTML

document.getElementById('link').innerHTML = 'The url'; 

編輯:http://jsfiddle.net/XVvyJ/1/

+0

的URL是JSON.parse(xhr.responseText).upload.links.imgur_page,但我怎麼能顯示呢?我很窮的Javascript。 – Tuan 2012-03-06 07:29:49

+0

我用「document.getElementById('link')。innerHTML」取代了「document.querySelector(」#link「)。href」,但它不起作用。 – Tuan 2012-03-06 07:37:28

+0

'#link'是什麼元素?你能告訴我HTML代碼嗎? (你可以編輯你的文章) – Raintree 2012-03-06 09:37:24