how to make file or image attachment like SO on a form
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);
}
精彩评论