【实例简介】
asp.net文件上传。。ajax
【实例截图】
【核心代码】
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.IO;
using System.Text;
namespace UploadDemo.project
{
public partial class UploadWeb : System.Web.UI.Page
{
string filename = null;
protected void Page_Load(object sender, EventArgs e)
{
try
{
HttpPostedFile postFile = Request.Files[0];
filename = Request.QueryString["filename"].ToString();
//开始上传
string _savedFileResult = UpLoadFile(postFile, filename);
Response.Write(_savedFileResult);
}
catch (Exception ex)
{
Response.Write("0|上传提交出错");
}
}
public string UpLoadFile(HttpPostedFile str, string filename)
{
return UpLoadFile(str, "/Authorization/", filename);
}
public string UpLoadFile(HttpPostedFile httpFile, string toFilePath, string filename)
{
try
{
//获取要保存的文件信息
//string filerealname = httpFile.FileName;
string filerealname = filename;
//获得文件扩展名
string fileNameExt = System.IO.Path.GetExtension(filerealname);
if (CheckFileExt(fileNameExt))
{
//检查保存的路径 是否有/结尾
if (toFilePath.EndsWith("/") == false) toFilePath = toFilePath "/";
//按日期归类保存
string datePath = "/";//DateTime.Now.ToString("yyyyMM") "/" DateTime.Now.ToString("dd") "/";
if (true)
{
toFilePath = datePath;
}
//物理完整路径
string toFileFullPath = System.Web.HttpContext.Current.Request.PhysicalApplicationPath toFilePath;
//检查是否有该路径 没有就创建
if (!System.IO.Directory.Exists(toFileFullPath))
{
Directory.CreateDirectory(toFileFullPath);
}
//得到服务器文件保存路径
string toFile = Server.MapPath("~" toFilePath);
string f_file = getName(filerealname);
//将文件保存至服务器
httpFile.SaveAs(toFile f_file);
return "1|文件上传成功";
}
else
{
return "0|文件不合法";
}
}
catch (Exception e)
{
return "0|文件上传失败,错误原因:" e.Message;
}
}
///
/// 获取文件名
///
///
///
private string getName(string fileNamePath)
{
string[] name = fileNamePath.Split('\\');
return name[name.Length - 1];
}
///
/// 检查是否为合法的上传文件
///
///
///
private bool CheckFileExt(string _fileExt)
{
string[] allowExt = new string[] { ".gif", ".jpg", ".jpeg", ".rar", ".png" };
for (int i = 0; i < allowExt.Length; i )
{
if (allowExt[i] == _fileExt) { return true; }
}
return false;
}
public static string GetFileName()
{
Random rd = new Random();
StringBuilder serial = new StringBuilder();
serial.Append(DateTime.Now.ToString("HHmmss"));
serial.Append(rd.Next(100, 999).ToString());
return serial.ToString();
}
}
}