- FileUpload Web Server Control
in ASP.NET, The FileUpload control can be used to allow users for sending a file from their own system to the web server. By using this control, user can upload pictures, text files, or other files.
The Article represents that how to work with the DropDownList control. Because the control is similar in many ways to the ListBox control, some of the links lead to topics for that control.
Handling Uploaded Files
When an user selected a file to upload and submitted the page, the file is uploaded as part of the request. The file is cached in its server memory. When the file has finished uploading, your page code runs.
the following ways helps you to handling the Uploaded file
- As a byte array exposed in the FileUpload control’s FileBytes property.
- As a stream exposed in the FileContent property.
- As an object of type HttpPostedFile in the PostedFile property. The PostedFile object exposes properties, such as the ContentType and ContentLength properties, which provide you with information about the uploaded file.
- Upload Files using FileUpload Web Control
using the following ways to Upload a file using FileUpload Control,
- Includes a FileUpload control in your page. by <asp:FileUpload />
- in Server side event such as page_load(),ensure the following
- Check that the FileUpload control has an uploaded file by testing its HasFile property.
- make sure that user uploading a file's type which must be according to your requirement types by MIME type.for example,if its image then it must be .gif,.jpg,etc
- Save the file to a location you specify. You can call the SaveAs method of the HttpPostedFile object. Alternatively, you can manage the uploaded file as a byte array or stream using the HttpPostedFile object's InputStream property.
the following code snippets demonstrates a FileUpload control
-
protected void Page_Load(object sender, EventArgs e)
{
if(IsPostBack)
{
Boolean FlagFile = false;
String FilePath = Server.MapFilePath("~/UploadedImages/");
if (FileUpload1.HasFile)
{
String FilePath =
System.IO.FilePath.GetExtension(FileUpload1.FileName).ToLower();
String[] NeedTypes = {".gif", ".png", ".jpeg", ".jpg"};
for (int i = 0; i < NeedTypes.Length; i++)
{
if (FilePath == NeedTypes[i])
{
FlagFile = true;
}
}
}
if (fileOK)
{
try
{
FileUpload1.PostedFile.SaveAs(FilePath
+ FileUpload1.FileName);
Label1.Text = "File uploaded!";
}
catch (Exception ex)
{
Label1.Text = "cannot find the file.";
}
}
else
{
Label1.Text = "invalid file format.";
}
}
}
-
- Related Links
-
f86c2eb1-ad58-46de-bf38-01ce1e98bc52|0|.0