在服務器端做文件上傳的過程中,如果使用web服務器短端的上傳控件去上傳文件的話,會導致頁面刷新一次,這樣對用戶的體驗就不是很友好了。ajaxfileupload.js是一款jQuery的異步上傳文件插件,使用簡單且容易上手。
public void FileUpload(HttpContext context)
{
try
{
context.Response.ContentType = "text/html";
string companyname = context.Request.Params["companyname"];
string billno = context.Request.Params["billno"];
string filename = context.Request.Params["filename"];
string name = companyname + "_" + billno + "_" + filename;
HttpFileCollection files = HttpContext.Current.Request.Files;
//指定上傳文件在服務器上的保存路徑
string savePath = context.Server.MapPath("~/upload/");
//檢查服務器上是否存在這個物理路徑,如果不存在則創建
if (!System.IO.Directory.Exists(savePath))
{
System.IO.Directory.CreateDirectory(savePath);
}
savePath = savePath + name;//上傳文件路徑
files[0].SaveAs(savePath);//保存文件
context.Response.Write(savePath);
}
catch (Exception ex)
{
context.Response.Write("FileUpload: " + ex.Message);
}
}