working
FileUpload Example in ASP.NET using C#
FileUpload.aspx (source code):
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="FileUpload.aspx.cs" Inherits="FileUpload" %>
<!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>
</head>
<body>
<form id="form1" runat="server">
<div>
<h2
style="color:Green">FileUpload
in ASP.NET 4 , C#</h2>
<asp:FileUpload
ID="fileupload1"
runat="server"
/>
<br
/>
<br
/>
<asp:Button
ID="button1"
Text="Upload"
runat="server"
Width="73px"
onclick="button1_Click"
/>
<br
/>
<br
/>
<asp:Label
ID="Label1"
runat="server"
Font-Bold="True"
ForeColor="#000099"></asp:Label>
</div>
</div>
</form>
</body>
</html>
FileUpload.aspx.cs (C# Code file):
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Collections.Generic;
using System.IO;//Please add this Namesape otherwise you get "Path " Error
public partial class FileUpload : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void button1_Click(object sender, EventArgs e)
{
if
(fileupload1.HasFile)
{
try
{
if
(fileupload1.PostedFile.ContentType ==
"image/jpeg")
{
if
(fileupload1.PostedFile.ContentLength < 512000)
{
string filename = Path.GetFileName(fileupload1.FileName);
fileupload1.SaveAs(Server.MapPath("~/") + filename);
Label1.Text = "File uploaded successfully!";
}
else
Label1.Text =
"File maximum size is 500 Kb";
}
else
Label1.Text =
"Only JPEG files are accepted!";
}
catch
(Exception
exc)
{
Label1.Text =
"The file could not be uploaded. The following error occured: "
+ exc.Message;
}
}
}
}
No comments:
Post a Comment