ASP.NET简单文件上传

一>使用FileUpload控件,将其拖入页面:

<%@ Page Title="hehe" Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="View.aspx.cs" Inherits="View" %>

<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<p>内容</p>
<form id="fileUpload" method="post" action="View.aspx" enctype="multipart/form-data">
<p>
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="btnUpload" runat="server" onclick="btnUpload_Click" Text="上传" />
</p>
</form>
<p><%=UpMessage %></p>
</asp:Content>

 

二>后端代码btnUpload_Click:

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;

public partial class View : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}

public string UpMessage = "";
public string[] UpTypes = { "jpeg", "gif", "png", "bmp" };
public string SaveDir = "Uploads";
protected void btnUpload_Click(object sender, EventArgs e)
{
if (!FileUpload1.HasFile) return;
if (FileUpload1.PostedFile.ContentLength > 10240000) {
UpMessage = "上传的文件必须小于10M!";
return;
}
if (CheckUpload(FileUpload1.PostedFile.ContentType) == false) {
UpMessage = "上传的文件类型不合法,请尝试这几种类型:jpg/png/gif/bmp";
return;
}
try
{
SaveDir = Server.MapPath("~/" + SaveDir);
if (!Directory.Exists(SaveDir)) Directory.CreateDirectory(SaveDir);
FileUpload1.PostedFile.SaveAs(SaveDir + "/" + FileUpload1.PostedFile.FileName);
UpMessage = "上传文件成功!";
}catch(Exception ex){
UpMessage = "上传文件过程中出错:" + ex.Message;
return;
}
}

public bool CheckUpload(string FileType) {
foreach (string UpType in UpTypes) {
if ("image/" + UpType == FileType) return true;
}
return false;
}
}

ASP.NET简单文件上传,古老的榕树,5-wow.com

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。