Application instance of FileUpload file upload control in ASP. NET

  • 2021-07-13 05:05:26
  • OfStack

Using the FileUpload control, you can provide a user with a way to send files from the user's computer to the server. This control is useful when allowing users to upload pictures, text files, or other files. The file to be uploaded will be submitted to the server as part 1 of the browser request during the postback. After the file is uploaded, you can manage the file with code.

After a general understanding of FileUpload under 1, let's look at the treatment methods of several practical applications of FileUpload under 1.

1.1 Upload multiple files at a time

To upload multiple files at a time, we can process each file separately like a single file. In addition, we can also use HttpFileCollection class to capture all files sent from Request object, and then process each file separately. The code is as follows:


protected void Button1_Click(object sender, EventArgs e)
{
    string filepath = Server.MapPath("upload") + "\\";
    HttpFileCollection uploadFiles = Request.Files;
    for (int i = 0; i < uploadFiles.Count; i++)
    {
        HttpPostedFile postedFile = uploadFiles[i];
        try
        {
            if (postedFile.ContentLength > 0)
            {
                Label1.Text += " Documents #" + (i + 1) + " : " + System.IO.Path.GetFileName(postedFile.FileName) + "<br/>";
                postedFile.SaveAs(filepath + System.IO.Path.GetFileName(postedFile.FileName));
            }
        }
        catch (Exception Ex)
        {
            Label1.Text += " An error occurred: " + Ex.Message;
        }
    }
}

2. Verification of uploaded file types

Verification of uploaded file types can be performed either on the client side or on the server side. The client can do this using validation controls, but today we'll focus on how to validate on the server side. The extension of the file has been obtained with GetExtension in the above cs file, and the verification of upload type can be realized with a little judgment:


protected void Button1_Click(object sender, EventArgs e)
{
    if (FileUpload1.HasFile)
    {
        fileExt = System.IO.Path.GetExtension(FileUpload1.FileName);
        if (fileExt == ".rar" || fileExt == ".zip")
        {
            try
            {
                FileUpload1.SaveAs(Server.MapPath("upload") + "\\" + FileUpload1.FileName);
                Label1.Text = " Client path: " + FileUpload1.PostedFile.FileName + "<br>" +
                              " Filename: " + System.IO.Path.GetFileName(FileUpload1.FileName) + "<br>" +
                              " File extension: " + System.IO.Path.GetExtension(FileUpload1.FileName) + "<br>" +
                              " File size: " + FileUpload1.PostedFile.ContentLength + " KB<br>" +
                              " Documents MIME Type: " + FileUpload1.PostedFile.ContentType + "<br>" +
                              " Save path: " + Server.MapPath("upload") + "\\" + FileUpload1.FileName;
            }
            catch (Exception ex)
            {
                Label1.Text = " An error occurred: " + ex.Message.ToString();
            }
        }
        else
        {
            Label1.Text = " Upload only rar , zip Files! ";
        }
    }
    else
    {
        Label1.Text = " No files have been selected for uploading! ";
    }
}

It should be noted that we can't rely too much on the client-side validation control and the server-side validation of the above methods, because users can avoid the above validation only by changing the file extension to the allowed type, which is not difficult for users.

3. Resolve file size limits

In ASP. NET 2.0, FileUpload defaults to upload a maximum of 4M, but we can change this default by modifying the relevant nodes in web. cofig, as follows:


<system.web>
    <httpRuntime maxRequestLength="40690" executionTimeout="6000" />
</system.web>

maxRequestLength represents the maximum number of files that can be uploaded, and executionTimeout represents the number of seconds an upload is allowed before ASP. NET is shut down.

4. Coexistence of "multipart/form-data" and Request

Once the form upload file is used in the ASP program (the enctype attribute value of form is multipart/form-data), the server can no longer use Request. Form to get the value of the form. This limitation no longer exists in ASP. NET 2.0:


protected void Button1_Click(object sender, EventArgs e)
{
    if (FileUpload1.HasFile)
    {
        try
        {
            FileUpload1.SaveAs(Server.MapPath("upload") + "\\" + FileUpload1.FileName);
            Label1.Text = " Upload file: " + FileUpload1.FileName + "<br>" +
                          " Description: " + Request.Form["TextBox1"];// You can also use "TextBox1.Text" To get the description
        }
        catch (Exception ex)
        {
            Label1.Text = " An error occurred: " + ex.Message.ToString();
        }
    }
    else
    {
        Label1.Text = " No files have been selected for uploading! ";
    }
}

Application example

Default.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>
</head>
<body>
 <form id="form1" runat="server">
  <asp:FileUpload ID="FileUpload1" runat="server" />
  <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" />
  <asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ControlToValidate="FileUpload1"
   ErrorMessage=" Must be  jpg Or gif Documents " ValidationExpression="^(([a-zA-Z]:)|(\\{2}\W+)\$?)(\\(\W[\W].*))+(.jpg|.Jpg|.gif|.Gif)$"></asp:RegularExpressionValidator>
 </form>

</body>
</html>

Default.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 _Default : System.Web.UI.Page
{
 protected void Page_Load(object sender, EventArgs e)
 {

 }
 protected void Button1_Click(object sender, EventArgs e)
 {
  String savePath = @"F:\111\";
  if (FileUpload1.HasFile)
  {
   String filename;
   filename = FileUpload1.FileName;
   savePath +=filename;
   FileUpload1.SaveAs(savePath);
   Page.Response.Write(FileUpload1.PostedFile.ContentType + FileUpload1.PostedFile.ContentLength+"<br>");
   Page.Response.Write("<img src='"+savePath+"'>");

  }
  else
  {
   Page.Response.Write("fff");
  }
 }

}

This example applies RegularExpressionValidator control to limit the upload of jpg, Jpg, gif, Gif format files. Of course, it is best to do 1 restrictions in the background. The specific operation methods have been explained above.


Related articles: