21 September 2008

How to upload file using ASP.NET in C#

UploadFile.aspx:

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

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 Pagetitle>
head>

<body>
<form id="form1" runat="server">
<div>
<input id="FileChooser" type="file" runat="server" />
<asp:Button ID="ButtonUpload" runat="server" Text="Upload" OnClick="ButtonUpload_Click" /><br />
<br />
<asp:Label ID="LabelStatus" runat="server" Width="36px">asp:Label>div>
form>
body>
html>

UploadFile.aspx.cs:

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 UploadFile : System.Web.UI.Page
{
private string uploadDirectory = @"D:\Testing projects\FileUpload\UploadedFiles";

protected void ButtonUpload_Click(object sender, EventArgs e)
{
if (this.FileChooser.PostedFile.ContentLength == 0)
this.LabelStatus.Text = "Can\'t upload zero length file.";
else
{
string fileName = this.getFileNameFromPath(this.FileChooser.PostedFile.FileName);
this.FileChooser.PostedFile.SaveAs(this.uploadDirectory + "\\"+ fileName);
this.LabelStatus.Text = "Uploaded to " + this.uploadDirectory;
}
}

private string getFileNameFromPath(string path)
{
int i = path.LastIndexOf('\\');
if (i == path.Length-1)
return null;
if (i < 0)
return path;
return path.Substring(i + 1);
}
}


0 Comments:

 

© 2007 t!ps n tr!cks: How to upload file using ASP.NET in C#



Template unik dari rohman


---[[ Skip to top ]]---