My favorites | Sign in
Project Home Downloads Wiki Issues Source
READ-ONLY: This project has been archived. For more information see this post.
Search
for
FileUploaderASPNET  
FileUploader con Ajax y evitar el PostBack
Updated Feb 4, 2010 by pepeluxx

Introduction

Para implementar el FileUploader con ajax y no necesitar PostBack para validar los ficheros he usado el componente de esta web: http://www.codeplex.com/fileuploadajax/Release/ProjectReleases.aspx?ReleaseId=8061

Details

El código es el siguiente:

En el Page_load:

 protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            if (cImagenMiniatura.IsPosting)
                this.managePost1();

            if (cImagenGrande.IsPosting)
                this.managePost2();
    }

Las funciones managePost1 y 2 son iguales pero cada una hace refrencia a una imagen. Pego una de ellas:

    private void managePost1()
    {
        HttpPostedFileAJAX pf = cImagenMiniatura.PostedFile;
        String usuario = (String)Context.Items["User"];
        String extension = "";

        if (pf.ContentType.Equals("image/gif"))
            extension = ".gif";
        else
            if (pf.ContentType.Equals("image/jpeg"))
                extension = ".jpg";

        if ((extension == ".gif") || (extension == ".jpg"))
            if (pf.ContentLength <= 1024 * 1024)
            {
                try
                {
                    File.Delete("WebNoticias/Panel/Tmp/" + usuario + "_miniatura" + extension);
                }
                catch {}

                cImagenMiniatura.SaveAs("~/Tmp", usuario + "_miniatura" + extension);
            }
            else
            {
                Label lbl = new Label();
                lbl.Text = "<script language='javascript'>" + Environment.NewLine + "window.alert('La imagen no puede exceder de 1Mb')</script>";
                Page.Controls.Add(lbl);
            }
        else
        {
            Label lbl = new Label();
            lbl.Text = "<script language='javascript'>" + Environment.NewLine + "window.alert('La imagen debe tener formato GIF o JPG')</script>";
            Page.Controls.Add(lbl);
        }
    }

Lo que hago es limitar a [GIF|JPG] y a un tamaño máximo de 1Mb Si es correcto guardo la foto en un archivo temporal como usuario_tipoimagen.extension

Una vez aceptado el formulario la guardamos así:

                        int foto1 = 0;
                        int foto2 = 0;

                        try
                        {
                            if (cImagenMiniatura.historial[0].Saved)
                                foto1 = 1;
                        }
                        catch { }

                        try
                        {
                            if (cImagenGrande.historial[0].Saved)
                                foto2 = 1;
                        }
                        catch { }

                        int fotos = foto1 + foto2;
                        DTOFichero dtoImagenMiniatura = null;
                        DTOFichero dtoImagenGrande = null;
                        String nombre;
                        String contentType;
                        String extension = "";
                        String origen = "";
                        String destino = "";
                        Random random = new Random();

                        // imagen miniatura
                        if (foto1 == 1)
                        {
                            nombre = cImagenMiniatura.historial[0].FileName_SavedAs.Substring(6, cImagenMiniatura.historial[0].FileName_SavedAs.Length-6);
                            contentType = cImagenMiniatura.historial[0].ContentType;

                            if (cImagenMiniatura.historial[0].ContentType.Equals("image/gif"))
                                extension = ".gif";
                            if (cImagenMiniatura.historial[0].ContentType.Equals("image/jpeg"))
                                extension = ".jpg";

                            if (extension == "")
                            {
                                Label lbl = new Label();
                                lbl.Text = "<script language='javascript'>" + Environment.NewLine + "window.alert('Ha ocurrido un error con la imagen pequeña y no va a guardar')</script>";
                                Page.Controls.Add(lbl);
                                dtoImagenMiniatura = new DTOFichero();
                            }
                            else
                            {
                                int aleatorio = random.Next(999999);

                                while (File.Exists("WebNoticias/Publica/Fotos/" + aleatorio.ToString() + extension))
                                    aleatorio = random.Next(999999);

                                origen = "WebNoticias/Panel/Tmp/" + nombre;
                                destino = "WebNoticias/Publica/Fotos/" + aleatorio.ToString() + extension;

                                try
                                {
                                    File.Move(origen, destino);
                                }
                                catch (Exception eeee)
                                {
                                    throw eeee;
                                }

                                dtoImagenMiniatura = new DTOFichero(0, destino, contentType, "");
                            }
                        }

Lo que hago es coger un número aleatorio para almacenarla en la carpeta destino (Fotos de la parte pública) comprobando antes que no exista ya ese nombre. El motivo de no usar el ID de la noticia como nombre de la foto es que tendria que hacer un crear y luego un modificar y aún no tengo implementado lo segundo :) ... y como el tiempo aprieta ....

Powered by Google Project Hosting