You must Sign In to post a response.
  • Category: .NET

    How to upload a file using asp.net


    Are you looking for a way to upload file using asp.net ? then read this thread to know more about it



    my requirement is like this

    upload file choosefile(here choose file is the button)
    when we click on choosefile button we select some files(i.e one window will come,though that we select any file in any drive).
    after one upload button and skip button.
    we click on upload button the uploaded file is upload in db.
    i want to open the uploaded file its opened.
  • #725273
    Reference:http://www.codeproject.com/Questions/272845/Uploading-files-to-database-in-Csharp

    private string SaveUpload(FileUpload fl)
    {
    if (fl.HasFile)
    {
    try
    {
    int version = 0;
    string filename = Path.GetFileName(fl.FileName);
    byte[] filedata = fl.FileBytes;
    string strCon = ConnectionStrings.Download;
    using (SqlConnection con = new SqlConnection(strCon))
    {
    con.Open();
    // Check version - if the file exists in the DB already, then increase version number.
    using (SqlCommand ver = new SqlCommand("SELECT MAX(version) FROM dlContent WHERE fileName=@FN", con))
    {
    ver.Parameters.AddWithValue("@FN", filename);
    object o = ver.ExecuteScalar();
    if (o != null && o != System.DBNull.Value)
    {
    // Exists already.
    version = (int) o + 1;
    }
    }
    // Stick file into database.
    using (SqlCommand ins = new SqlCommand("INSERT INTO dlContent (iD, fileName, description, dataContent, version, uploadedOn) " +
    "VALUES (@ID, @FN, @DS, @DT, @VS, @UD)", con))
    {
    ins.Parameters.AddWithValue("@ID", Guid.NewGuid());
    ins.Parameters.AddWithValue("@FN", filename);
    ins.Parameters.AddWithValue("@DS", "");
    ins.Parameters.AddWithValue("@DT", filedata);
    ins.Parameters.AddWithValue("@VS", version);
    ins.Parameters.AddWithValue("@UD", DateTime.Now);
    ins.ExecuteNonQuery();
    }
    }
    return string.Format("{0} uploaded, version = {1}", filename, version);
    }
    catch (Exception ex)
    {
    return "The file could not be uploaded. The following error occured: " + ex.Message;
    }
    }
    return "Please select a file.";
    }

  • #725278
    You need to use ASP:FileUpload control. it works as per your requirement on click of browse you will get windows browser prompt to choose the file
    check following code snippet

    <asp:FileUpload id="FileUploadControl1" runat="server" />
    <asp:Button runat="server" id="btnUpload" text="Upload file" />
    <br /><br />
    //on click of browse file button you will a get a file choose window after file selection you can click on upload button and execute following code

    //save the file to folder
    string szFileName = Path.GetFileName(FileUploadControl1.FileName);
    FileUploadControl1.SaveAs("D:\\" + szFileName);


    your file will get save to D:\\

    Thanks
    Koolprasd2003
    Editor, DotNetSpider MVM
    Microsoft MVP 2014 [ASP.NET/IIS]

  • #725283
    Hi,

    It is not advisable to save the files in database because your database size will grow and you will have a major performance impact. Best option would be keep the files in a folder and save the path in the databse.

    Create a folder called "Uploads" and upload the files in this folder.

    protected void btnFileUpload_Click(object sender, ImageClickEventArgs e)
    {
    if (FileUpload.HasFile)
    try
    {
    FileUpload.SaveAs(Server.MapPath("~/Uploads/" + FileUpload.FileName.ToString()));
    //Code to save the file path in database goes here.

    }
    catch (Exception ex)
    {
    lblStatus.Text = "ERROR: While uploading the document. " + ex.Message.ToString();
    }
    else
    {
    lblStatus.Text = "Please select a valid file.";
    }
    Response.Clear();
    }


    Let me know if you have any doubt on this code.


    Regards,
    Asheej T K

  • #725286
    You can try below example code snippet for How to upload a file using asp.net on upload button
    private void Btn1_Click(object sender, System.EventArgs e)
    {
    string stringFilename;
    TryExample
    {
    stringFilename = File3.PostedFile.FName;
    stringFilename = System.IO.Path.GetFileName(stringFilename);
    File1.PostedFile.SaveAs(@"C:\"+stringFilename);
    }
    catch(Exception exce)
    {
    Response.Write(exce);
    }
    }
    Beside above code snippet I refer some useful link
    http://rrmtricks.blogspot.in/2012/08/aspnet-classic-fileupload-control-using.html
    http://www.4guysfromrolla.com/webtech/091201-1.shtml

  • #725297
    Hi,

    Refer below sample code. Here, i saved the uploaded file in Sharepoint site, so based on your requirement you update the data.


    private void Upload_TenderVsActual(string Doc_Id, string SNo, string Revision)
    {
    SPCurrentSite objCurrentSite = new SPCurrentSite();
    SPDocumentLibrary objFile = new SPDocumentLibrary();
    string Msg = "Excel file Uploaded Successfully...";
    //these are the columns i created in Sharepoint site
    Hashtable taskHash = new Hashtable();
    taskHash["Dwg_No"] = Doc_Id;
    taskHash["Dwg_Rev_No"] = Revision;
    taskHash["SNo"] = SNo;
    taskHash["Doc_No"] = Doc_No;

    string FileName = flUploadTA.FileName;
    string FileType = FileName.Substring(FileName.IndexOf('.') + 1);
    byte[] File = flUploadTA.FileBytes;

    string FileName1 = Path.GetFileName(flUploadTA.PostedFile.FileName);
    try
    {
    //Here i add file to sharepoint DocumentLibrary
    objFile.AddLibraryItemAttachment(objCurrentSite.SiteURL, objCurrentSite.WebSiteName, "TenderVsActual", File, Doc_No + "-" + Revision + "-" + SNo + "." + FileType, taskHash);

    }
    catch (Exception ex)
    {
    Msg = ex.Message;
    }
    }


    Update your code based upon your requirement.

    --------------------------------------------------------------------------------
    Give respect to your work, Instead of trying to impress your boss.

    N@veen
    Blog : http://naveens-dotnet.blogspot.in/

  • #725368
    try like this complete code

    table structure

    create table stud([ID] [int] IDENTITY(1,1) ,sname varchar(50),simage image)


    .aspx page

    Enter Student Name<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox><br/>
    Select student image to be uploaded<asp:FileUpload ID="FileUpload1" runat="server" /><br/>
    <asp:Button ID="Button1" runat="server" Text="Add New Student" onclick="Button1_Click" /><br/>
    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false"
    DataKeyNames="sid" >
    <Columns>
    <asp:TemplateField HeaderText="Student name">
    <ItemTemplate>
    <%#Eval("sname")%>
    </ItemTemplate>
    </asp:TemplateField>
    <asp:TemplateField HeaderText="Student image">
    <ItemTemplate>
    <asp:Image ID="Image1" runat="server" ImageUrl='<%# "Default3.aspx?ID=" + Eval("sid")%>' Height="100" Width="120"/>
    </ItemTemplate>
    </asp:TemplateField>
    </Columns>
    </asp:GridView>


    .aspx.cs code

    using System.Data.SqlClient;
    using System.Data;
    using System.IO;
    using System.Configuration;
    public partial class _Default : System.Web.UI.Page
    {
    SqlConnection sqlcon = new SqlConnection(ConfigurationManager.ConnectionStrings["Con"].ConnectionString);
    SqlCommand sqlcmd = new SqlCommand();
    SqlDataAdapter da = new SqlDataAdapter();
    DataTable dt = new DataTable();
    String sname, query;
    byte[] filebyte = null;

    protected void Page_Load(object sender, EventArgs e)
    {
    if (!Page.IsPostBack)
    {
    LoadGrid();
    }
    }
    void LoadGrid()
    {
    sqlcon.Open();
    sqlcmd = new SqlCommand("select * from stud", sqlcon);
    da = new SqlDataAdapter(sqlcmd);
    dt.Clear();
    da.Fill(dt);
    if (dt.Rows.Count > 0)
    {
    GridView1.DataSource = dt;
    GridView1.DataBind();
    }
    else
    {
    GridView1.DataBind();
    }
    sqlcon.Close();
    }
    //Insert into database
    protected void Button1_Click(object sender, EventArgs e)
    {
    if (FileUpload1.HasFile)
    {
    sname = TextBox1.Text;
    filebyte = convertByte(FileUpload1);
    sqlcon.Open();
    query = "insert into stud(sname,simage) values(@sname,@simage)";
    SqlCommand cmd = new SqlCommand(query, sqlcon);
    cmd.Parameters.Add("@sname", SqlDbType.VarChar).Value = sname;
    cmd.Parameters.Add("@simage", SqlDbType.Image).Value = filebyte;
    cmd.CommandType = CommandType.Text;
    cmd.ExecuteNonQuery();
    sqlcon.Close();
    TextBox1.Text = "";
    LoadGrid();
    }
    }
    public byte[] convertByte(FileUpload FileControl)
    {
    Stream fs = default(Stream);
    byte[] bytes1 = null;
    byte[] postfile = null;
    fs = FileControl.PostedFile.InputStream;
    BinaryReader br1 = new BinaryReader(fs);
    bytes1 = br1.ReadBytes(FileControl.PostedFile.ContentLength);
    postfile = bytes1;
    return postfile;
    }
    }



    Default3.aspx.cs

    using System.Data.SqlClient;
    using System.Data;
    using System.IO;


    public partial class Default3 : System.Web.UI.Page
    {
    SqlConnection sqlcon = new SqlConnection(ConfigurationManager.ConnectionStrings["Con"].ConnectionString);
    SqlCommand sqlcmd = new SqlCommand();
    SqlDataAdapter da = new SqlDataAdapter();
    DataTable dt = new DataTable();
    DataSet ds = new DataSet();
    byte[] b = null;

    protected void Page_Load(object sender, EventArgs e)
    {
    if (!Page.IsPostBack)
    {
    int sid = Convert.ToInt32(Request.QueryString["ID"]);
    SqlConnection sqlcon = new SqlConnection(ConfigurationManager.ConnectionStrings["Con"].ConnectionString);
    SqlCommand sqlcmd = new SqlCommand("Select simage from stud where sid =@sid", sqlcon);
    sqlcmd.Parameters.Add("@sid", SqlDbType.Int).Value = sid;
    sqlcmd.CommandType = System.Data.CommandType.Text;
    sqlcon.Open();
    da = new SqlDataAdapter(sqlcmd);
    da.Fill(dt);
    if (dt.Rows.Count > 0)
    {
    b = ((byte[])dt.Rows[0][0]);
    MemoryStream ms = new MemoryStream(b);
    Response.ContentType = "image/jpeg";
    Response.BinaryWrite(b);
    }
    }
    }
    }

    Regards
    N.Ravindran
    Your Hard work never fails


  • This thread is locked for new responses. Please post your comments and questions as a separate thread.
    If required, refer to the URL of this page in your new post.