2012-01-08 19 views
12

के साथ अपलोड की गई फ़ाइल को पकड़ें, मैं <input type='file'> टैग में अपलोड की गई फ़ाइल को पकड़ना चाहता हूं।jQuery इनपुट प्रकार = 'फ़ाइल'

जब मैं $ ('# इनपुट आईडी') करता हूं। वैल(), यह केवल फ़ाइल के नाम को पकड़ता है, वास्तविक फ़ाइल नहीं। फ़ाइल उदाहरणों को पुनः प्राप्त करने

http://hacks.mozilla.org/2011/03/the-shortest-image-uploader-ever/

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: 
    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); 
} 

उत्तर

13

उपयोग event.target.fileschange घटना के लिए:

मैं इस का पालन करने की कोशिश कर रहा हूँ।

$('#inputId').change(function(e) { 
    var files = e.target.files; 

    for (var i = 0, file; file = files[i]; i++) { 
    console.log(file); 
    } 
}); 

अधिक जानकारी के लिए यहां एक नज़र: http://www.html5rocks.com/en/tutorials/file/dndfiles/

यह समाधान फ़ाइल एपीआई जो सभी ब्राउज़र द्वारा समर्थित नहीं है का उपयोग करता है - http://caniuse.com/#feat=fileapi देखते हैं।

+4

अतिरिक्त जानकारी: एक ही अपलोड की गई फ़ाइल हमेशा 'e.target.files [0]' में होती है, उस बिंदु पर आपको 'लूप' की आवश्यकता नहीं होती है। – DanFromGermany

3

यह संभवतः HTML5 files संपत्ति का जिक्र कर रहा है। w3 और नमूना jsfiddle

+0

एचएम, तो पुराने ब्राउज़र के साथ जावास्क्रिप्ट छवि अपलोड करना संभव नहीं है? शर्म :( –

+1

आप हमेशा एक आईफ्रेम पर लक्ष्य के साथ एक नियमित रूप का उपयोग कर सकते हैं। यह कोड के लिए कम सुंदर है लेकिन काम करता है। –

संबंधित मुद्दे