Home Backend Development C#.Net Tutorial asp.net fileupload control to upload files and upload multiple files

asp.net fileupload control to upload files and upload multiple files

Jan 11, 2017 am 10:39 AM

1、前台文件 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>asp.net fileupload控件上传文件_www.jb51.net</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="必须是 jpg或者gif文件" ValidationExpression="^(([a-zA-Z]:)|(\\{2}\W+)\$?)(\\(\W[\W].*))+(.jpg|.Jpg|.gif|.Gif)$"></asp:RegularExpressionValidator>
</form>
</body>
</html>
Copy after login

2、后端代码 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=&#39;"+savePath+"&#39;>");
}
else
{
Page.Response.Write("fff");
}
 }
}
Copy after login

去掉绿色部分就可上传任何文件,它是用一个正则表达式来验证上传文件的类型

在ASP.NET 2.0中使用FileUpload服务器控件很容易的就能将文件上传到服务器。

1、aspx文件代码

<%@ 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>FileUpload上传文件示例-jb51.net</title>
</head>
<body>
 <form id="form1" runat="server">
 <div>
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="Button1" runat="server" _disibledevent="Button1_Click" Text="上传文件" /><br />
<asp:Label ID="Label1" runat="server" Height="269px" Text="Label" Width="360px"></asp:Label></div>
 </form>
</body>
</html>
Copy after login

2、后端代码 aspx.cs:

protected void Button1_Click(object sender, EventArgs e)
{
 if (FileUpload1.HasFile)
 {
try
{
FileUpload1.SaveAs(Server.MapPath("upload") + "\\" + FileUpload1.FileName);
Label1.Text = "客户端路径:" + FileUpload1.PostedFile.FileName + "<br>" +
"文件名:" + System.IO.Path.GetFileName(FileUpload1.FileName) + "<br>" +
"文件扩展名:" + System.IO.Path.GetExtension(FileUpload1.FileName) + "<br>" +
"文件大小:" + FileUpload1.PostedFile.ContentLength + " KB<br>" +
"文件MIME类型:" + FileUpload1.PostedFile.ContentType + "<br>" +
"保存路径:" + Server.MapPath("upload") + "\\" + FileUpload1.FileName;
}
catch (Exception ex)
{
Label1.Text = "发生错误:" + ex.Message.ToString();
}
 }
 else
 {
Label1.Text = "没有选择要上传的文件!";
 }
}
Copy after login

1、asp.net fileupload多文件上传的例子

使用fileupload实现多文件上传,可以像传单个文件那样对每个文件单独进行处理,除此之外,还可以使用HttpFileCollection类捕获从Request对象发送来的所有文件,然后再单独对每个文件进行处理。

后端代码 aspx.cs:

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 += "文件 #" + (i + 1) + ":" + System.IO.Path.GetFileName(postedFile.FileName) + "<br/>";
 postedFile.SaveAs(filepath + System.IO.Path.GetFileName(postedFile.FileName));
}
}
catch (Exception Ex)
{
Label1.Text += "发生错误: " + Ex.Message;
}
 }
}
Copy after login

2、上传文件类型的验证
对上传文件类型的验证既可以在客户端进行,也可以在服务器端进行。
客户端可以使用验证控件来进行,这里重点介绍如何在服务器端进行验证。

以上cs文件中已用GetExtension获取了文件的扩展名,只要稍加判断即可实现上传类型验证:
aspx.cs:

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 = "客户端路径:" + FileUpload1.PostedFile.FileName + "<br>" +
"文件名:" + System.IO.Path.GetFileName(FileUpload1.FileName) + "<br>" +
"文件扩展名:" + System.IO.Path.GetExtension(FileUpload1.FileName) + "<br>" +
"文件大小:" + FileUpload1.PostedFile.ContentLength + " KB<br>" +
"文件MIME类型:" + FileUpload1.PostedFile.ContentType + "<br>" +
"保存路径:" + Server.MapPath("upload") + "\\" + FileUpload1.FileName;
}
catch (Exception ex)
{
 Label1.Text = "发生错误:" + ex.Message.ToString();
}
}
else
{
Label1.Text = "只允许上传rar、zip文件!";
}
 }
 else
 {
Label1.Text = "没有选择要上传的文件!";
 }
}
Copy after login


注意,不能过分依赖于客户端验证控件和服务器端上述方法的验证,因为用户只需将文件扩展名更改为允许的类型就可以避开上边的验证,这对用户来说并不是件困难的事情。

3、解决文件大小限制
在ASP.NET 2.0中FileUpload默认上传文件最大为4M,不过可以在web.cofig中修改相关节点来更改这个默认值,相关节点如下:

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

maxRequestLength表示可上传文件的最大值,executionTimeout表示ASP.NET关闭前允许发生的上载秒数。

4、"multipart/form-data"和Request共存

在ASP程序中一旦使用表单上传文件(form的enctype属性值为multipart/form-data),服务器端就不能再用Request.Form来获取表单的值,这种限制在ASP.NET 2.0中已不存在了:

aspx.cs:

protected void Button1_Click(object sender, EventArgs e)
{
 if (FileUpload1.HasFile)
 {
try
{
FileUpload1.SaveAs(Server.MapPath("upload") + "\\" + FileUpload1.FileName);
Label1.Text = "上传文件:" + FileUpload1.FileName + "<br>" +
"说明:" + Request.Form["TextBox1"];//也可以用"TextBox1.Text"来获取说明
}
catch (Exception ex)
{
Label1.Text = "发生错误:" + ex.Message.ToString();
}
 }
 else
 {
Label1.Text = "没有选择要上传的文件!";
 }
}
Copy after login


更多asp.net fileupload控件上传文件与多文件上传相关文章请关注PHP中文网!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1677
14
PHP Tutorial
1279
29
C# Tutorial
1257
24
The Continued Relevance of C# .NET: A Look at Current Usage The Continued Relevance of C# .NET: A Look at Current Usage Apr 16, 2025 am 12:07 AM

C#.NET is still important because it provides powerful tools and libraries that support multiple application development. 1) C# combines .NET framework to make development efficient and convenient. 2) C#'s type safety and garbage collection mechanism enhance its advantages. 3) .NET provides a cross-platform running environment and rich APIs, improving development flexibility.

C# as a Versatile .NET Language: Applications and Examples C# as a Versatile .NET Language: Applications and Examples Apr 26, 2025 am 12:26 AM

C# is widely used in enterprise-level applications, game development, mobile applications and web development. 1) In enterprise-level applications, C# is often used for ASP.NETCore to develop WebAPI. 2) In game development, C# is combined with the Unity engine to realize role control and other functions. 3) C# supports polymorphism and asynchronous programming to improve code flexibility and application performance.

Deploying C# .NET Applications to Azure/AWS: A Step-by-Step Guide Deploying C# .NET Applications to Azure/AWS: A Step-by-Step Guide Apr 23, 2025 am 12:06 AM

How to deploy a C# .NET app to Azure or AWS? The answer is to use AzureAppService and AWSElasticBeanstalk. 1. On Azure, automate deployment using AzureAppService and AzurePipelines. 2. On AWS, use Amazon ElasticBeanstalk and AWSLambda to implement deployment and serverless compute.

C# and the .NET Runtime: How They Work Together C# and the .NET Runtime: How They Work Together Apr 19, 2025 am 12:04 AM

C# and .NET runtime work closely together to empower developers to efficient, powerful and cross-platform development capabilities. 1) C# is a type-safe and object-oriented programming language designed to integrate seamlessly with the .NET framework. 2) The .NET runtime manages the execution of C# code, provides garbage collection, type safety and other services, and ensures efficient and cross-platform operation.

C# .NET: Building Applications with the .NET Ecosystem C# .NET: Building Applications with the .NET Ecosystem Apr 27, 2025 am 12:12 AM

How to build applications using .NET? Building applications using .NET can be achieved through the following steps: 1) Understand the basics of .NET, including C# language and cross-platform development support; 2) Learn core concepts such as components and working principles of the .NET ecosystem; 3) Master basic and advanced usage, from simple console applications to complex WebAPIs and database operations; 4) Be familiar with common errors and debugging techniques, such as configuration and database connection issues; 5) Application performance optimization and best practices, such as asynchronous programming and caching.

.NET Framework vs. C#: Decoding the Terminology .NET Framework vs. C#: Decoding the Terminology Apr 21, 2025 am 12:05 AM

.NETFramework is a software framework, and C# is a programming language. 1..NETFramework provides libraries and services, supporting desktop, web and mobile application development. 2.C# is designed for .NETFramework and supports modern programming functions. 3..NETFramework manages code execution through CLR, and the C# code is compiled into IL and runs by CLR. 4. Use .NETFramework to quickly develop applications, and C# provides advanced functions such as LINQ. 5. Common errors include type conversion and asynchronous programming deadlocks. VisualStudio tools are required for debugging.

C# .NET Development: A Beginner's Guide to Getting Started C# .NET Development: A Beginner's Guide to Getting Started Apr 18, 2025 am 12:17 AM

To start C#.NET development, you need to: 1. Understand the basic knowledge of C# and the core concepts of the .NET framework; 2. Master the basic concepts of variables, data types, control structures, functions and classes; 3. Learn advanced features of C#, such as LINQ and asynchronous programming; 4. Be familiar with debugging techniques and performance optimization methods for common errors. With these steps, you can gradually penetrate the world of C#.NET and write efficient applications.

C# and .NET: Understanding the Relationship Between the Two C# and .NET: Understanding the Relationship Between the Two Apr 17, 2025 am 12:07 AM

The relationship between C# and .NET is inseparable, but they are not the same thing. C# is a programming language, while .NET is a development platform. C# is used to write code, compile into .NET's intermediate language (IL), and executed by the .NET runtime (CLR).

See all articles