Comentario: A continuación usamos la nueva API de archivo de características de HTML 5 para cargar archivos y mostrar el porcentaje de progreso de los archivos de carga. La intención es como esta: cuando se selecciona un archivo, se muestra la información del archivo actual.
Aquí combinamos ASP.NET MVC como servidor, y también puede usar otros idiomas del servidor. Veamos el HTML de este fragmento:@Using (html.beginform ("cargar", "inicio", formmethod.post, new {enctype = "multipart/form-data",})))
{
<div>
<etiqueta para = "archivo">
Imagen de carga: </etiqueta>
<input type = "file" múltiple = "múltiple" onchange = "filesElected ();" />
</div>
<div>
</div>
<div>
</div>
<div>
</div>
<div>
<input type = "button" valor = "imagen de carga" />
</div>
<div>
</div>
}
El JavaScript relacionado es el siguiente:
function filesElected () {
var file = document.getElementById ('filetoUpload'). Archivos [0];
if (file) {
var filesize = 0;
if (file.size> 1024 * 1024)
filesize = (math.round (file.size * 100 / (1024 * 1024)) / 100) .ToString () + 'mb';
demás
filesize = (math.round (file.size * 100 /1024) / 100) .ToString () + 'kb';
document.getElementById ('FileName'). InnerHtml = 'name:' + file.name;
document.getElementById ('filesize'). innerhtml = 'size:' + filesize;
document.getElementById ('fileType'). innerhtml = 'type:' + file.type;
}
}
function uploadFile () {
var fd = new FormData ();
fd.append ("filetoUpload", document.getElementById ('filetoUpload'). Archivos [0]);
var xhr = new xmlhttprequest ();
xhr.upload.addeventListener ("Progress", uploadProgress, false);
xhr.addeventListener ("Load", uploadComplete, false);
XHR.AdDeventListener ("Error", carguefailed, falso);
XHR.AdDeventListener ("abort", cargada de carga, falso);
xhr.open ("Post", "Inicio/Subida");
XHR.SEND (FD);
}
function uploadProgress (EVT) {
if (evt.lengthComputable) {
var porcentcomplete = math.round (evt.loaded * 100 /evt.total);
document.getElementById ('ProgressNumber'). InnerHtml = porcentialcomplete.ToString () + '%';
}
demás {
document.getElementById ('ProgressNumber'). InnerHtml = 'no se puede calcular';
}
}
function uploadComplete (EVT) {
/ * Este evento se plantea cuando el servidor envía una respuesta */
alerta (evt.target.esponsetext);
}
function uploadFailed (EVT) {
alerta ("Hubo un error intentando cargar el archivo");
}
function uploadCanceled (EVT) {
alerta ("La carga ha sido cancelada por el usuario o el navegador eliminó la conexión");
}
El anterior es el JavaScript nativo, que ejecuta la función Velacta de archivos en el evento OnChange, y ejecuta la función de carga de carga en el botón Click. Aquí, use xmlhttprequest para implementar el archivo de carga AJAX. Tenga en cuenta que el código puede funcionar en Firefox 14. IE 9 actualmente no admite la API de archivo, por lo que puede participar aquí. El código del lado del servidor es muy simple:
HomeController de clase pública: controlador
{
Public ActionResult Index ()
{
Vista de retorno ();
}
/// <summary>
/// Sube los archivos especificados.
/// </summary>
/// <amamr> los archivos. </marc>
/// <devoluciones> ActionResult </Devuelve>
[Httppost]
Public ActionResult Subload (httppostedFileBase [] filetoUpload)
{
foreach (archivo httppostedFileBase en filetoUpload)
{
string path = system.io.path.combine (server.mappath ("~/app_data"), system.io.path.getfilename (file.fileName));
file.saveas (ruta);
}
Verbag.message = "archivo (s) cargado con éxito";
return redirectToAction ("índice");
}
}
Autor: Petter Liu