upload file to server and save path in BD with .NET

0

I have a web form within which one of its fields the function is to upload a file to the server (I already have a folder where the files are stored) and the path to save it in a BD. How can I do so that with just the button to send the form you can upload the file automatically and also save the form data?

Currently this procedure is done separately, ie I upload the file first and then I save the data but the user can be confused and not save (upload to the server) the file and only send the form data, that's why I just want to have the button to send the form and I would have to do the two functions: 1. Save the data of the form fields in the database and 2. Upload the file to the server

As I said before I have to upload the file first and then save it in the DB, and that's how I do it:

<table width="682" border="0" cellpadding="0" cellspacing="0" class="table">
    <tr>
        <td align="center" class="rowData">
            <table border="0" width="75%">
                <tr>
                    <td colspan="2">
                        <asp:TextBox runat="server" ID="txtIDAnuncio" Visible="false"></asp:TextBox>
                        <asp:TextBox runat="server" ID="txtOpAnuncio" Visible="false"></asp:TextBox>&nbsp;
                    </td>
                </tr>

                <tr>
                    <td align="right" style="width: 126px">Titulo del Anuncio:
                    </td>
                    <td align="left">
                        <asp:TextBox runat="server" ID="txtTitulo" MaxLength="20" SkinID="txtGral" Width="168px"></asp:TextBox>
                        <asp:RequiredFieldValidator runat="server" ID="RequiredFieldValidator1" ControlToValidate="txtTitulo" ErrorMessage="*Ingrese un titulo para el anuncio.">*</asp:RequiredFieldValidator>
                    </td>
                </tr>
                <tr>
                    <td align="right" style="width: 126px">Cuerpo del Anuncio:
                    </td>
                    <td align="left">
                        <asp:TextBox runat="server" ID="txtCuerpo" MaxLength="20" SkinID="txtGral" Width="168px"></asp:TextBox>
                        <asp:RequiredFieldValidator runat="server" ID="RequiredFieldValidator5" ControlToValidate="txtCuerpo" ErrorMessage="*Ingrese el cuerpo del anuncio.">*</asp:RequiredFieldValidator>
                    </td>
                </tr>
                <tr>
                    <td align="right" style="width: 126px">Archivo:
                    </td>
                    <td align="left">
                        <asp:FileUpload ID="FileUpload1" runat="server" />
                        <hr />
                        <asp:Button ID="btnUpload" Text="Upload" runat="server" OnClick="UploadFile" />
                        <br />
                        <asp:Label ID="lblMessage" ForeColor="Green" runat="server" />
                        <asp:Label ID="lblMessage1" ForeColor="Green" runat="server" />
                        <asp:TextBox runat="server" ID="txtArchivo" MaxLength="20" SkinID="txtGral" Width="168px" Visible="false"></asp:TextBox>
                    </td>
                </tr>
                <tr>
                    <td align="right" style="width: 126px">Pagina principal:
                    </td>
                    <td align="left">
                        <asp:CheckBox runat="server" ID="chkStatus" Checked="true" Text="" />
                    </td>
                </tr>
                <tr>
                    <td align="right" style="width: 126px">Inicio de vigencia:
                    </td>
                    <td align="left">
                        <asp:TextBox runat="server" ID="txtFechai" MaxLength="20" SkinID="txtGral" Width="168px"></asp:TextBox>
                        <asp:RequiredFieldValidator runat="server" ID="RequiredFieldValidator3" ControlToValidate="txtFechai" ErrorMessage="*Seleccione la fecha inicial del anuncio.">*</asp:RequiredFieldValidator>
                    </td>
                </tr>
                <tr>
                    <td align="right" style="width: 126px">Fin de vigencia:
                    </td>
                    <td align="left">
                        <asp:TextBox runat="server" ID="txtFechaf" MaxLength="20" SkinID="txtGral" Width="168px"></asp:TextBox>
                        <asp:RequiredFieldValidator runat="server" ID="RequiredFieldValidator4" ControlToValidate="txtFechaf" ErrorMessage="*Seleccione la fecha final del anuncio.">*</asp:RequiredFieldValidator>
                    </td>
                </tr>
            </table>
        </td>
    </tr>
    <tr>
        <td align="center" colspan="2">&nbsp;</td>
    </tr>
    <tr>
        <td>
            <hr />
        </td>
    </tr>
    <tr>
        <td>
            <asp:ValidationSummary runat="server" ID="sErrors" DisplayMode="List" SkinID="vsGral" ShowSummary="true" />
        </td>
    </tr>
    <tr>
        <td colspan="2" align="center">
            <asp:Button runat="server" ID="BtnAceptar" Text="Aceptar" CausesValidation="true" Width="100px" OnClick="BtnAceptar_Click" />&nbsp;
        <asp:Button runat="server" ID="BtnCancel" Text="Regresar" CausesValidation="false" Width="100px" OnClick="BtnCancel_Click" />
        </td>
    </tr>

</table>

codebehind

protected void BtnAceptar_Click(object sender, EventArgs e)
{
    try
    {
        oAnuncios = new clAnunciosPortal();

        EntAnuncios = new EntidadAnunciosPortal();
        EntAnuncios.IDAnuncio = Convert.ToInt32(txtIDAnuncio.Text);
        EntAnuncios.IconoAnuncio = txtIcono.Text;
        EntAnuncios.TituloAnuncio = txtTitulo.Text;
        EntAnuncios.CuerpoAnuncio = txtCuerpo.Text;

        if (lblMessage.Text != "")
        {
            //EntAnuncios.UrlArchivo = FileUpload1.FileName.ToString();
            EntAnuncios.UrlArchivo = lblMessage.Text;
        }
        else
        {
            EntAnuncios.UrlArchivo = txtArchivo.Text;
        }

        EntAnuncios.PaginaPrincipalAnuncio = chkStatus.Checked;
        EntAnuncios.FechaDesdeAnnuncio = Convert.ToDateTime(txtFechai.Text);
        EntAnuncios.FechaHastaAnuncio = Convert.ToDateTime(txtFechaf.Text);
        EntAnuncios.IDUsuarioAltaAnuncio = Convert.ToInt32(Session["ID_usuario"]);
        EntAnuncios.FechaAltaAnuncio = Convert.ToDateTime(DateTime.Now);
        EntAnuncios.IDUsuarioModificaAnuncio = Convert.ToInt32(Session["ID_usuario"]);

        switch (txtOpAnuncio.Text)
        {
            case "1":
                if (oAnuncios.InsertarAnuncio(EntAnuncios) > 0)
                {           
                    this.Confirmacion();
                }
                else
                {
                    this.AlertError("No se pudo agregar el registro.");
                }

                break;

            default:
                break;

        }

    }
    catch (Exception exc)
    { }
}

protected void UploadFile(object sender, EventArgs e)
{
    string folderPath = Server.MapPath("~/AAA/BBB/CCC/");


    if (!Directory.Exists(folderPath))
    {

        Directory.CreateDirectory(folderPath);
    }


    FileUpload1.SaveAs(folderPath + Path.GetFileName(FileUpload1.FileName));


    lblMessage.Text = Path.GetFileName(FileUpload1.FileName);
    lblMessage1.Text = " ha sido subido exitosamente.";
}
    
asked by Ivxn 22.11.2017 в 03:50
source

1 answer

1

If you notice, the upload component button and the form button do the same, they launch a Click event that activates the sending of the COMPLETE form, that is, the data of the included form is sent the FileUpload component. So now what you are doing is two submit, one when sending the file and another when sending the data and this is not necessary.

In the Click event in the codebehind you can pick up the file sent by FileUpload. Just try to put the code of the UploadFile method in the click event and you will see that everything works the same and you have access to the FileName.

Additionally you can check if the file has been uploaded with this instruction

if(FileUploadControl.HasFile)
{
    try
    {
        if(FileUploadControl.PostedFile.ContentType == "image/jpeg")
        {
            if(FileUploadControl.PostedFile.ContentLength < 102400)
            {
                string filename = Path.GetFileName(FileUploadControl.FileName);
                FileUploadControl.SaveAs(Server.MapPath("~/") + filename);
                StatusLabel.Text = "Upload status: File uploaded!";
            }
            else
                StatusLabel.Text = "Upload status: The file has to be less than 100 kb!";
        }
        else
            StatusLabel.Text = "Upload status: Only JPEG files are accepted!";
    }
    catch(Exception ex)
    {
        StatusLabel.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
    }
}
    
answered by 22.11.2017 / 10:11
source