我创建了一个简单的表单,允许用户上传图像并提交表单。表单数据上传到Google电子表格。为了在谷歌电子表格中填充图像,我需要图像拥有自己的网址。我正在测试imgur的API,并且在完成此操作之后它非常有效:https://hacks.mozilla.org/2011/03/the-shortest-image-uploader-ever/。
现在我的表单为该特定图片生成了一个网址,如何使用该网址填充我的Google电子表格?我正在考虑使用一个文本框,它会在生成时自动填充href,但我不知道该怎么做。
在imgur的API生成链接后,是否有更简单的方法将链接粘贴到我的电子表格中?
我在这里包含了它的工作演示。
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();
fd.append("image", file); // Append the file
var xhr = new XMLHttpRequest(); // Create the XHR
xhr.open("POST", "https://api.imgur.com/3/image.json"); // Boooom!
xhr.onload = function() {
// Big win!
document.querySelector("#link").href = JSON.parse(xhr.responseText).data.link;
document.body.className = "uploaded";
}
xhr.setRequestHeader('Authorization', 'Client-ID 490be95195679b1'); // Imgur API key here
/* And now, we send the formdata */
xhr.send(fd);
}

#link, p , div {display: none}
.uploading div {display: none}
.uploaded div {display: none}
.uploading p {display: inline}
.uploaded #link {display: inline}

<input type="file" onchange="upload(this.files[0])"><br />
<!-- this is the text box we could paste the url in -->
<input tyle="text">
<p>Uploading...</p>
<a id="link">Link to imgur file</a>
&#13;
答案 0 :(得分:1)
这将使用网址填充文本框
document.getElementById("urlText").value = JSON.parse(xhr.responseText).data.link;
<input type="text" id="urlText" name="urlText">
完整代码:
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();
fd.append("image", file); // Append the file
var xhr = new XMLHttpRequest(); // Create the XHR
xhr.open("POST", "https://api.imgur.com/3/image.json"); // Boooom!
xhr.onload = function() {
// Big win!
document.querySelector("#link").href = JSON.parse(xhr.responseText).data.link;
document.body.className = "uploaded";
document.getElementById("urlText").value = JSON.parse(xhr.responseText).data.link;
}
xhr.setRequestHeader('Authorization', 'Client-ID 490be95195679b1'); // Imgur API key here
/* And now, we send the formdata */
xhr.send(fd);
}
&#13;
#link, p , div {display: none}
.uploading div {display: none}
.uploaded div {display: none}
.uploading p {display: inline}
.uploaded #link {display: inline}
&#13;
<input type="file" onchange="upload(this.files[0])"><br />
<input type="text" id="urlText" name="urlText">
<p>Uploading...</p>
<a id="link">Link to imgur file</a>
&#13;