ASP.NET - How to browse and upload a file to server in asp.net

Asked By aman on 28-Sep-11 12:56 AM
hi all,

i want to create a file uploader to the site but unable to do so ......please help me with some good example.

thanks
Web Star replied to aman on 28-Sep-11 01:01 AM
only you need to use input contorl to set type equal to file for borwse the window to select the file for upload
<input id="filMyFile" type="file" runat="server">
and get selected file by using
 filMyFile.PostedFile
this simple example every where on net you will found
here is good one sample
http://www.codeproject.com/KB/aspnet/fileupload.aspx
Web Star replied to aman on 28-Sep-11 01:03 AM
there are also good example with complete code to upload file on server in asp.net
http://msdn.microsoft.com/en-us/library/aa479405.aspx
http://support.microsoft.com/kb/323246

Suchit shah replied to aman on 28-Sep-11 01:26 AM
<%@ Page Language="C#" %>

<script runat="server">
    protected void Button1_Click(object sender, EventArgs e)
    {
      if (FileUpload1.HasFile)
        try
        {
          FileUpload1.SaveAs("C:\\Uploads\\" +
           FileUpload1.FileName);
          Label1.Text = "File name: " +
           FileUpload1.PostedFile.FileName + "<br>" +
           FileUpload1.PostedFile.ContentLength + " kb<br>" +
           "Content type: " +
           FileUpload1.PostedFile.ContentType;
        }
        catch (Exception ex)
        {
          Label1.Text = "ERROR: " + ex.Message.ToString();
        }
      else
      {
        Label1.Text = "You have not specified a file.";
      }
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Upload Files</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
      <asp:FileUpload ID="FileUpload1" runat="server" /><br />
      <br />
      <asp:Button ID="Button1" runat="server" OnClick="Button1_Click"
     Text="Upload File" />&nbsp;<br />
      <br />
      <asp:Label ID="Label1" runat="server"></asp:Label></div>
    </form>
</body>
</html>
Suchit shah replied to aman on 28-Sep-11 01:27 AM
C# code

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack == true)
{
AddRows();
}
}

private void AddRows()
{
try
{
if (hidCurRow.Value != "" && hidCurRow.Value != "0")
{
DecreaseCount();
}
else if(hidCurRow.Value == "")
{
IncreaseCount();
}

for (int count = 1; count < tblMin.Rows.Count; count++)
{
tblMin.Rows.RemoveAt(1);
}

int maxRows = Convert.ToInt32(hidMax.Value);
string[] arrRows = hidRow.Value.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
for (int count = 1; count <= maxRows; count++)
{
Boolean isAdd = false;
for (int incount = 0; incount < arrRows.Length; incount++)
{
if (arrRows[incount] == count.ToString())
{
isAdd = true;
break;
}
}

if (isAdd == true)
{
TableRow tr = new TableRow();

TableCell tcfu = new TableCell();
FileUpload fup = new FileUpload();
fup.ID = "fu" + count.ToString();
tcfu.Controls.Add(fup);

TableCell tcbtn = new TableCell();
Button bt = new Button();
bt.ID = "btn" + count.ToString();
bt.Text = "Remove";
bt.Attributes.Add("onclick", "DecreaseRow('" + count.ToString() + "');");
tcbtn.Controls.Add(bt);


tr.Cells.Add(tcfu);
tr.Cells.Add(tcbtn);

tblMin.Rows.Add(tr);
}
}
}
catch
{

}
}

private void IncreaseCount()
{
string strVal = hidMax.Value;
if (strVal != "")
{
int iMax = Convert.ToInt32(strVal);
iMax = iMax + 1;
hidMax.Value = iMax.ToString();

if (hidRow.Value != "")
{
hidRow.Value = hidRow.Value + "," + iMax.ToString();
}
else
{
hidRow.Value = iMax.ToString();
}
}
}

private void DecreaseCount()
{
string strCurRow = hidCurRow.Value;
string[] arrRows = hidRow.Value.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
hidRow.Value = "";
for (int count = 0; count < arrRows.Length; count++)
{
if (arrRows[count] != strCurRow)
{
if (hidRow.Value == "")
{
hidRow.Value = arrRows[count];
}
else
{
hidRow.Value = hidRow.Value + "," + arrRows[count];
}
}
}
}

protected void btnAdd_Click(object sender, EventArgs e)
{

}

protected void btnSubmit_Click(object sender, EventArgs e)
{
if (hidRow.Value != "")
{
string[] strVal = hidRow.Value.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
for (int count = 0; count < strVal.Length; count++)
{
FileUpload fup = new FileUpload();
fup = (FileUpload)tblMin.FindControl("fu" + strVal[count]);
if (fup != null)
{
if (fup.PostedFile != null && fup.FileName != "")
{
//your code here
}
}
}
}
}
}





ASPX

 




<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Page</title>
<script type="text/javascript" language="javascript">

//set current row no to delete function DecreaseRow(rowNo)
{
var hid = document.getElementById('<%= hidCurRow.ClientID %>');
hid.value = rowNo;

}

//clear the delete row hiddent file to show that its insert
function IncreseRows()
{
var hid = document.getElementById('<%= hidCurRow.ClientID %>');
hid.value = "";

}

//Set zero for Submit
function SetZero()
{
var hid = document.getElementById('<%= hidCurRow.ClientID %>');
hid.value = "0";
}
</script>
</head>
<body>

<form id="form1" runat="server">
<asp:Table ID="tblMin" runat="server">
<asp:TableHeaderRow>
<asp:TableHeaderCell>
File
</asp:TableHeaderCell>
<asp:TableHeaderCell>
Remove
</asp:TableHeaderCell>
</asp:TableHeaderRow>
<asp:TableRow>
<asp:TableCell>
<asp:FileUpload ID="fu1" runat="server" />
</asp:TableCell>
<asp:TableHeaderCell>
<asp:Button ID="btn1" runat="server" Text="Remove" OnClientClick="return DecreaseRow('1');" />
</asp:TableHeaderCell>
</asp:TableRow>
</asp:Table>
<asp:Button ID="btnAdd" runat="server" OnClick="btnAdd_Click" Text="Add" OnClientClick="return IncreseRows();" />
<asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="btnSubmit_Click" OnClientClick="SetZero();"/><br />
<asp:HiddenField ID="hidMax" runat="server" value="1"/>
<asp:HiddenField ID="hidRow" runat="server" value="1"/>
<asp:HiddenField ID="hidCurRow" runat="server"/>
</form>
</body>
</html>
Anoop S replied to aman on 28-Sep-11 03:36 AM
Refer this code

<%@ Page Language="C#" %>

<script runat="server">
    protected void Button1_Click(object sender, EventArgs e)
    {
        if (FileUpload1.HasFile)
            try
            {
                FileUpload1.SaveAs("C:\\Uploads\\" + 
                     FileUpload1.FileName);
                Label1.Text = "File name: " +
                     FileUpload1.PostedFile.FileName + "<br>" +
                     FileUpload1.PostedFile.ContentLength + " kb<br>" +
                     "Content type: " +
                     FileUpload1.PostedFile.ContentType;
            }
            catch (Exception ex)
            {
                Label1.Text = "ERROR: " + ex.Message.ToString();
            }
        else
        {
            Label1.Text = "You have not specified a file.";
        }
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Upload Files</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:FileUpload ID="FileUpload1" runat="server" /><br />
        <br />
        <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" 
         Text="Upload File" />&nbsp;<br />
        <br />
        <asp:Label ID="Label1" runat="server"></asp:Label></div>
    </form>
</body>
</html>


refer this ->Learn how to use the new FileUpload server control
http://msdn.microsoft.com/en-us/library/aa479405.aspx
dipa ahuja replied to aman on 28-Sep-11 07:07 AM
Untitled document
try this code. This will save your file in the images folder and if the image file already exist then it wil rename it.
 
<asp:FileUpload ID="FileUpload1" runat="server"></asp:FileUpload>
<asp:Button ID="UploadButton" Text="Upload file" OnClick="UploadButton_Click" runat="server"/>
 
 
protected void UploadButton1_Click(object sender, EventArgs e)
{
   if (FileUpload1.HasFile)
   {
     // Call a helper method routine to save the file.
     // Specify the path to save the uploaded file to.
     string savePath = Server.MapPath("images/");
 
     // Get the name of the file to upload.
     string fileName = FileUpload1.FileName;
 
     // Create the path and file name to check for duplicates.
     string pathToCheck = savePath + fileName;
 
     // Create a temporary file name to use for checking duplicates.
     string tempfileName = "";
 
     // Check to see if a file already exists with the, same name as the file to upload.      
    if (File.Exists(pathToCheck))
     {
       int counter = 2;
       while (File.Exists(pathToCheck))
       {
         // if a file with this name already exists,
         // prefix the filename with a number.
         tempfileName = counter.ToString() + fileName;
         pathToCheck = savePath + tempfileName;
         counter++;
       }
 
       fileName = tempfileName;
 
       // Notify the user that the file name was changed.
       UploadStatusLabel.Text = "A file with the same name already exists." +
         "<br />Your file was saved as " + fileName;
     }
     else
     {
       // Notify the user that the file was saved successfully.
       UploadStatusLabel.Text = "Your file was uploaded successfully.";
     }
 
     // Append the name of the file to upload to the path.
     savePath += fileName;
     FileUpload1.SaveAs(savePath);
    
    Image1.ImageUrl = "images/" + FileUpload1.FileName;
   }
   else
   {
     // Notify the user that a file was not uploaded.
     UploadStatusLabel.Text = "You did not specify a file to upload.";
   }
}