Subir archivos en ASP.net sin utilizar el control del servidor FileUpload


¿Cómo puedo obtener un ASP.net formulario web (v3. 5) para publicar un archivo usando un <input type="file" />?

No estoy interesado en usar el ASP.net FileUpload server control.

Gracias por sus sugerencias.

Author: Ronnie Overby, 2009-02-20

10 answers

En su aspx:

<form id="form1" runat="server" enctype="multipart/form-data">
 <input type="file" id="myFile" name="myFile" />
 <asp:Button runat="server" ID="btnUpload" OnClick="btnUploadClick" Text="Upload" />
</form>

En código detrás:

protected void btnUploadClick(object sender, EventArgs e)
{
    HttpPostedFile file = Request.Files["myFile"];

    //check file was submitted
    if (file != null && file.ContentLength > 0)
    {
        string fname = Path.GetFileName(file.FileName);
        file.SaveAs(Server.MapPath(Path.Combine("~/App_Data/", fname)));
    }
}
 125
Author: mathieu,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-06-18 19:42:23

Aquí hay una solución sin depender de ningún control del lado del servidor, al igual que OP ha descrito en la pregunta.

Código HTML del lado del cliente:

<form action="upload.aspx" method="post" enctype="multipart/form-data">
    <input type="file" name="UploadedFile" />
</form>

Page_Load método de carga.aspx:

if(Request.Files["UploadedFile"] != null)
{
    HttpPostedFile MyFile = Request.Files["UploadedFile"];
    //Setting location to upload files
    string TargetLocation = Server.MapPath("~/Files/");
    try
    {
        if (MyFile.ContentLength > 0)
        {
            //Determining file name. You can format it as you wish.
            string FileName = MyFile.FileName;
            //Determining file size.
            int FileSize = MyFile.ContentLength;
            //Creating a byte array corresponding to file size.
            byte[] FileByteArray = new byte[FileSize];
            //Posted file is being pushed into byte array.
            MyFile.InputStream.Read(FileByteArray, 0, FileSize);
            //Uploading properly formatted file to server.
            MyFile.SaveAs(TargetLocation + FileName);
        }
    }
    catch(Exception BlueScreen)
    {
        //Handle errors
    }
}
 38
Author: Aycan Yaşıt,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-09-22 09:26:52

Tendrás que establecer el atributo enctype de form a multipart/form-data; a continuación, puede acceder al archivo cargado utilizando la colección HttpRequest.Files.

 22
Author: csgero,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-08-26 10:35:53

Utilice el control HTML con un atributo de servidor runat

 <input id="FileInput" runat="server" type="file" />

Luego en asp.net Codebehind

 FileInput.PostedFile.SaveAs("DestinationPath");

También hay algunas opciones 3'rd party que mostrarán el progreso si desea

 9
Author: cgreeno,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-02-20 14:01:17

Sí, puede lograr esto mediante el método ajax post. en el lado del servidor puede usar httphandler. Por lo tanto, no estamos utilizando ningún control de servidor según su requisito.

Con ajax también puede mostrar el progreso de la carga.

Tendrá que leer el archivo como inputstream.

using (FileStream fs = File.Create("D:\\_Workarea\\" + fileName))
    {
        Byte[] buffer = new Byte[32 * 1024];
        int read = context.Request.GetBufferlessInputStream().Read(buffer, 0, buffer.Length);
        while (read > 0)
        {
            fs.Write(buffer, 0, read);
            read = context.Request.GetBufferlessInputStream().Read(buffer, 0, buffer.Length);
        }
    } 

Código de muestra

function sendFile(file) {              
        debugger;
        $.ajax({
            url: 'handler/FileUploader.ashx?FileName=' + file.name, //server script to process data
            type: 'POST',
            xhr: function () {
                myXhr = $.ajaxSettings.xhr();
                if (myXhr.upload) {
                    myXhr.upload.addEventListener('progress', progressHandlingFunction, false);
                }
                return myXhr;
            },
            success: function (result) {                    
                //On success if you want to perform some tasks.
            },
            data: file,
            cache: false,
            contentType: false,
            processData: false
        });
        function progressHandlingFunction(e) {
            if (e.lengthComputable) {
                var s = parseInt((e.loaded / e.total) * 100);
                $("#progress" + currFile).text(s + "%");
                $("#progbarWidth" + currFile).width(s + "%");
                if (s == 100) {
                    triggerNextFileUpload();
                }
            }
        }
    }
 7
Author: Samuel Joy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-03-26 15:08:52

La Solicitud.La colección de archivos contiene todos los archivos cargados con su formulario, independientemente de si provienen de un control FileUpload o de un <input type="file"> escrito manualmente.

Así que puede escribir una etiqueta de entrada de archivo simple en el medio de su formulario web, y luego leer el archivo cargado desde la Solicitud.Colección de archivos.

 4
Author: David,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-02-20 13:43:01

Como otros tienen respuesta, la Petición.Files es una HttpFileCollection que contiene todos los archivos que se publicaron, solo necesita pedirle a ese objeto el archivo de la siguiente manera:

Request.Files["myFile"]

Pero qué sucede cuando hay más de un marcado de entrada con el mismo nombre de atributo:

Select file 1 <input type="file" name="myFiles" />
Select file 2 <input type="file" name="myFiles" />

En el lado del servidor la solicitud de código anterior.Files ["myFile"] solo devuelve un objeto HttpPostedFile en lugar de los dos archivos. He visto en .net 4.5 de un método de extensión llamado GetMultiple pero para versiones anteriores no existe, para el caso propongo el método de extensión como:

public static IEnumerable<HttpPostedFile> GetMultiple(this HttpFileCollection pCollection, string pName)
{
        for (int i = 0; i < pCollection.Count; i++)
        {
            if (pCollection.GetKey(i).Equals(pName))
            {
                yield return pCollection.Get(i);
            }
        }
}

Este método de extensión devolverá todos los objetos HttpPostedFile que tengan el nombre "MyFiles" en la HttpFileCollection si existe alguno.

 3
Author: Joey O,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-05-20 21:33:10

HtmlInputFile control

He usado esto todo el tiempo.

 2
Author: Lurker Indeed,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-02-20 13:36:31

Aquí hay un artículo de Code Project con un proyecto descargable que pretende resolver esto. Descargo de responsabilidad: No he probado este código. http://www.codeproject.com/KB/aspnet/fileupload.aspx

 1
Author: Bork Blatt,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-02-20 13:37:42
//create a folder in server (~/Uploads)
 //to upload
 File.Copy(@"D:\CORREO.txt", Server.MapPath("~/Uploads/CORREO.txt"));

 //to download
             Response.ContentType = ContentType;
             Response.AppendHeader("Content-Disposition", "attachment;filename=" + Path.GetFileName("~/Uploads/CORREO.txt"));
             Response.WriteFile("~/Uploads/CORREO.txt");
             Response.End();
 0
Author: Jean Pierre Yenque,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-05-31 03:14:38