合作开发的另一个问题:上传文件。
WebForm1.aspx:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="UploadTest01.WebForm1" %>
<!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">
<div>
<asp:Button ID="btn_upload" runat="server" Text="btn_upload" OnClick ="btn_upload_Click" />
<asp:FileUpload ID="upload" runat="server" />
<br />
<asp:Label ID="lab_upload" runat="server" Text="lab_upload"></asp:Label>
</div>
</form>
</body>
</html>
WebForm1.aspx.cs:
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 UploadTest01
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
#region 上传文件
protected void btn_upload_Click(object sender, EventArgs e)
{
UploadMethod("~/UpLoadFiles/Files/");
}
private void UploadMethod(String UpLoadFilePath)
{
bool fileOK = false;
//文件的上传路径
string path = Server.MapPath(UpLoadFilePath);
//判断上传文件夹是否存在,若不存在,则创建
if (!Directory.Exists(path))
{
//创建文件夹
Directory.CreateDirectory(path);
}
if (upload.HasFile)
{
//如果选择了文件则执行
//获取上传文件的类型
string fileExtesion = System.IO.Path.GetExtension(upload.FileName).ToLower();
//获取没有扩展名的文件名
string result = System.IO.Path.GetFileNameWithoutExtension(upload.FileName);
//允许上传的类型
string[] allowExtesions = { ".doc", ".xls", ".rar", ".zip", ".ppt" };
for (int i = 0; i < allowExtesions.Length; i++)
{
if (fileExtesion == allowExtesions[i])
{
//文件格式正确 允许上传
fileOK = true;
}
}
if (fileOK)
{
try
{
//以时间命名
string newname = System.DateTime.Now.ToString("yyyyMMddHHmmssffff");//声称文件名,防止重复
newname = result + newname + fileExtesion;
upload.PostedFile.SaveAs(path + newname);
Session["filename"] = newname;
lab_upload.Text = "上传成功";
}
catch (Exception)
{
lab_upload.Text = "上传失败";
//throw ex;
}
}
else
{
lab_upload.Text = "上传文件类型错误";
}
}
else
{
//尚未选择文件
lab_upload.Text = "尚未选择任何文件,请选择文件";
return;
}
}
#endregion
}
}
通过UploadMethod方法,传入要上传的路径,就可以把文件上传到指定的目录下。