2012-01-08 36 views
12

Quiero tomar el archivo cargado en una etiqueta <input type='file'>.jQuery tomar un archivo cargado con tipo de entrada = 'archivo'

Cuando hago $ ('# inputId'). Val(), solo toma el nombre del archivo, no el archivo en sí.

estoy tratando de seguir esta:

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

Respuesta

13

Uso event.target.files para change evento para recuperar las instancias de archivos.

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

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

un vistazo aquí para obtener más información: http://www.html5rocks.com/en/tutorials/file/dndfiles/

Esta solución utiliza la API de archivos que no está soportado por todos los navegadores - ver http://caniuse.com/#feat=fileapi.

+4

Información adicional: Un único archivo cargado siempre está en 'e.target.files [0]', en ese punto no necesita el bucle 'for'. – DanFromGermany

3

Esto probablemente se refiere a la propiedad HTML5 files. Ver w3 y muestra jsfiddle

+0

Hm, ¿entonces la carga de imágenes con javascript no es posible con los navegadores más antiguos? Lástima :( –

+1

Siempre puedes usar un formulario regular con el objetivo para un iframe. Es menos lindo de codificar pero funciona. –

Cuestiones relacionadas