以下示例来自官方MSND ,如有疑问请致电微软
本来想用 JS 在客户端实现图片预览功能,但是发现网上一大堆说不安全。
前台
<html >
<head id="Head1" runat="server">
<title>FileUpload Example</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h4>Select a file to upload:</h4>
<asp:FileUpload id="FileUpload1" runat="server"></asp:FileUpload>
<br /><br />
<asp:Button id="UploadButton" Text="Upload file" OnClick="UploadButton_Click" runat="server"></asp:Button>
<asp:Image ID="Image1" runat="server" Height="180" Width="150" />
<hr />
<asp:Label id="UploadStatusLabel" runat="server"></asp:Label>
</div>
</form>
</body>
</html>
后台
namespace SafeRiskPrj.WEB
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
/// <summary>
/// 注意:
///
/// 如果savePath 不存在,报错...所以必须确保savePath目录存在,权限
/// 如果FileName在服务器已经存在,将覆盖文件,所以文件名必须重新定义
/// 当遇到大文件上传需要修改配置文件: maxRequestLength 单位 k
/// 例如 <httpRuntime useFullyQualifiedRedirectUrl="true" maxRequestLength="1024000" executionTimeout="900"/>
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void UploadButton_Click(object sender, EventArgs e)
{
string saveDir = @"\Uploads\";
string errmsg="";
//string appPath = Request.PhysicalApplicationPath;
string appPath = Server.MapPath(".");
if (FileUpload1.HasFile)
{
string fileName = Server.HtmlEncode(FileUpload1.FileName);
string extension = System.IO.Path.GetExtension(fileName);
if ((extension == ".gif") || (extension == ".jpg") || (extension == ".JPG") || (extension == ".GIF"))
{
int fileSize = FileUpload1.PostedFile.ContentLength;
if (fileSize < 4194304)
{
string newfilename = System.DateTime.Now.ToString("yyyyMMddhhmmssffff") + extension;
string savePath = appPath + saveDir + newfilename;
FileUpload1.SaveAs(savePath);
this.Image1.ImageUrl = saveDir + newfilename;
errmsg = "文件上传成功";
}
else {
errmsg = "文件太大,无法上传";
}
}
else {
errmsg = "文件格式不正确!";
}
}
else
{
errmsg = "请选择需要上传的文件";
}
UploadStatusLabel.Text = errmsg;
}
}
}