2011-08-25 56 views
2

我已经看到了一些用于上传文件和图像的PHP脚本,但没有发现它们是我需要的。如何使文件或图像附件像SO这样的形式

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

任何想法,我可以做什么?

+0

你为什么要允许用户下载他们刚刚上传的文件。我可以理解上传/存储供以后使用,但现在上传并提供可能有点多余。 –

+0

@Marc B:你的意思是像imageshack和相关? – Konerak

+0

这是因为当我在我的公司制作票时,我喜欢通过屏幕截图或文件ID ......我们不允许在此过程中使用第三方程序或网站。 – Bulvak

回答

2

Working Example

是,当用户添加文件,使用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); 
} 
+0

我只能上传图片不是文件?如果我还想上传文件? – Bulvak

相关问题