如何在表单上创建像SO一样的文件或图像附件 [英] how to make file or image attachment like SO on a form

查看:65
本文介绍了如何在表单上创建像SO一样的文件或图像附件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看到了一些用于上传文件和图像的PHP脚本,但没有发现它们是我需要的。

基本上我有一个表单: http:// jsfiddle .net / MwnSn / 11 / 和底部的textarea部分,我想添加一个附加图像/文件,以便当用户从他们的计算机中选择一个文件或图像时,它会在textarea中创建一些URL那么用户可以提交表单,而查看器只需在地址栏中输入网址以下载文件或查看图像...我知道可以将此图像或文件下载到我的虚拟主机中并让用户获得网址直接下载或查看,但这可能是一个不可靠的烦人,因为我需要创建一个cron作业,以清理每周的混乱....



任何关于我能做什么的想法?

rel =nofollow> 工作示例

是的,当用户添加文件时,使用 http://api.imgur.com/examples

 函数上传(文件){

//文件来自< input>标记或从Drag'n Drop
//文件是图像吗?

if(!file ||!file.type.match(/ image。* /))return;

//这是!
//让我们构建一个FormData对象

var fd = new FormData();
fd.append(image,file); //追加文件
fd.append(key,6528448c258cff474ca9701c5bab6927);
//获取您自己的密钥:http://api.imgur.com/

//创建XHR(跨域XHR FTW !!!)
var xhr = new XMLHttpRequest();
xhr.open(POST,http://api.imgur.com/2/upload.json); // Boooom!
xhr.onload = function(){
//大赢!
//图像的URL是:
document.getElementById('TextAreaId')。innerHTML = JSON.parse(xhr.responseText).upload.links.imgur_page;
}
//好的,我不处理这些错误。给读者一个练习题。
//现在,我们发送表单数据
xhr.send(fd);
}


I have seen some PHP scripts for uploading files and images but didn't find them to be what I need.

Basically I have a form: http://jsfiddle.net/MwnSn/11/ and the textarea section at bottom, I would like to add an attach image/file so that when a user chooses a file or image from their computer it creates into someform of URL in the textarea so then the user can submit form and the viewer just puts the url in their address bar to download the file or view the image...I know there could be a way to download this image or file into my webhost and let the user get the url to download or view it directly but that might be annoying an unreliable because I would need to create a cron job to clean that mess up weekly....

Any ideas on what I could do?

解决方案

Working Example

Yes, when the user adds the file, using http://api.imgur.com/examples:

function upload(file) {

  // file is from a <input> tag or from Drag'n Drop
  // Is the file an image?

  if (!file || !file.type.match(/image.*/)) return;

  // It is!
  // Let's build a FormData object

  var fd = new FormData();
  fd.append("image", file); // Append the file
  fd.append("key", "6528448c258cff474ca9701c5bab6927");
  // Get your own key: http://api.imgur.com/

  // Create the XHR (Cross-Domain XHR FTW!!!)
  var xhr = new XMLHttpRequest();
  xhr.open("POST", "http://api.imgur.com/2/upload.json"); // Boooom!
  xhr.onload = function() {
    // Big win!
    // The URL of the image is:
    document.getElementById('TextAreaId').innerHTML = JSON.parse(xhr.responseText).upload.links.imgur_page;
   }
   // Ok, I don't handle the errors. An exercice for the reader.
   // And now, we send the formdata
   xhr.send(fd);
 }

这篇关于如何在表单上创建像SO一样的文件或图像附件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆