一、Aspx页面:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="FileUploadDemo.aspx.cs" Inherits="WebApplication1.FileUploadDemo" %>
二、Aspx后台代码:
using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.UI;using System.Web.UI.WebControls;using System.IO;namespace WebApplication1{ public partial class FileUploadDemo : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void btnOk_Click(object sender, EventArgs e) { if (this.fileUpload.HasFile) { string fileName = this.fileUpload.PostedFile.FileName; // 客户端文件路径 string extension = System.IO.Path.GetExtension(fileName); if (extension.ToLower() != ".jpg" && extension.ToLower() != ".png") { ScriptManager.RegisterStartupScript(this, this.GetType(), "msg", "alert('只允许jpg 和 png!');", true); return; } string pathBase = "D:\\UploadFile"; if (!Directory.Exists(pathBase)) Directory.CreateDirectory(pathBase); string webFilePath = Path.Combine(pathBase, fileName); // 数据库保存文件路径(相对全路径) this.fileUpload.SaveAs(webFilePath); // 使用 SaveAs 方法保存文件 ScriptManager.RegisterStartupScript(this, this.GetType(), "msg", "alert('上傳成功,我們會盡快進行核對!');", true); } } }}