上传图片到目录

前台:

代码
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="UploadFiles.aspx.cs" Inherits="UploadFiles" %>

<!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>无标题页</title>
</head>
<body>
<form id="form1" runat="server">
<asp:Label ID="Label1" runat="server" Text="请选择上传图片:"></asp:Label>
<asp:FileUpload ID="FileUpload1" runat="server" /><br />
<asp:Button ID="upload" runat="server" OnClick="upload_Click" Text="上传" />
<asp:Label ID="Label2" runat="server" Text="Label" Width="101px"></asp:Label>
</form>
</body>
</html>

后台:

代码
using System;
using System.Data;
using System.Configuration;
using System.Collections;
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 UploadFiles : System.Web.UI.Page
{

protected void Page_Load(object sender, EventArgs e)
{

}
protected void upload_Click(object sender, EventArgs e)
{
Boolean fileOK
= false;//标记测试文件的类型是否符合
string filepath;
String path
= Server.MapPath("~/image/");
if (FileUpload1.HasFile)
{
string fileExtension = System.IO.Path.GetExtension(FileUpload1.FileName).ToLower();
string[] allowedExtensions ={ ".jpg" };
for (int i = 0; i < allowedExtensions.Length; i++)
{
if (fileExtension == allowedExtensions[i])
{
fileOK
= true;
}
}
}
if (FileUpload1.PostedFile.ContentLength > 10240000)
{
fileOK
= false;
}
if (fileOK)
{
try
{
FileUpload1.PostedFile.SaveAs(path
+ FileUpload1.FileName);
filepath
= "~/image/" + FileUpload1.FileName;
Label2.Text
= "文件上传成功!"+filepath;

}
catch (Exception ex)
{
Label2.Text
= "上传失败!";
}
}
else
{
Label2.Text
= "无法实现上传,请检测上传文件大小和格式是否符合要求!";
}
}
}

原文地址:https://www.cnblogs.com/JingG/p/1782510.html