单文件上传:
ASPX:
<div>
<!-- 文件上传 -->
<asp:FileUpload ID="FileUpload1" runat="server" /><asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" /><asp:Label ID="Label1" runat="server" Text="Label"></asp:Label><br />
<asp:Image ID="Image1" runat="server" />
</div>
/////////////////////////////////////////////
CS:
protected void Page_Load(object sender, EventArgs e)
{ } protected void Button1_Click(object sender, EventArgs e)
{
if (this.FileUpload1.HasFile)
{
// 判断是否有文件要上传
// SaveAs()添加的是物理路径,不能够使用虚拟路径
// string dirName = "~/files/"; // 这样不行,因为这个是虚拟路径
string dirName = Server.MapPath("~/files/"); // 将虚拟路径转换为物理路径 // 判断路径是否存在,不存在那么创建路径
if (!Directory.Exists(dirName))
{
Directory.CreateDirectory(dirName); // 创建路劲
}
string fileName = Guid.NewGuid().ToString(); // 获取唯一不重复的标识
//string oldFullDirName = this.FileUpload1.PostedFile.FileName; // 获取物理路径(例如:D:\a.jpg)
string oldFileName = this.FileUpload1.FileName; // 获取文件名(例如:a.jpg)
string ext = Path.GetExtension(oldFileName); // 获取扩展名(.jpg)
string fileNameNew = fileName + ext; // 构建新文件名
string filePathV = string.Format("~/files/{0}", fileNameNew); // 虚拟路径
string filePath = Server.MapPath(filePathV); // 物理路径
this.FileUpload1.SaveAs(filePath); // 另存为
long sizeM = this.FileUpload1.PostedFile.ContentLength / (); // 获取文件大小,这里使用单位为K
this.Label1.Text = string.Format("文件大小:{0:#.000},类型:{1},保存到:{2}", sizeM, this.FileUpload1.PostedFile.ContentType, filePath);
this.Image1.ImageUrl = filePathV; // 显示图片,使用虚拟路径即可,当然物理路径也行
}
else
{
this.Label1.Text = "请先选择文件再上传....";
}
}
/////////////////////////////////////////////////////////////////////
config:
<system.web>
<!-- 开启debug -->
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" />
<!-- 默认允许上传大小为4M,这里设置为允许上传图片大小为10M -->
<httpRuntime maxRequestLength=""/>
</system.web>