JQUERY+ASP.NET的AJAX文件上传
JS部分代码如下
function TestUp()
{
ajaxFileUpload("FileUpload1");
}
function ajaxFileUpload(obfile_id)
{
//准备提交处理
$("#loading_msg").html("<img src=/images/DotAjax.gif />");
//开始提交
$.ajax
({
type: "POST",
url:"ajaxUpFile.ashx",
data:"upfile="+$("#"+obfile_id).val(),
success:function (data, status)
{
//alert(data);
var stringArray = data.split("|");
if(stringArray[0]=="1")
{
//stringArray[0] 成功状态(1为成功,0为失败)
//stringArray[1] 上传成功的文件名
//stringArray[2] 消息提示
$("#divmsg").html("<img src=/images/note_ok.gif />"+stringArray[2]+" 文件地址:"+stringArray[1]);
$("#filepreview").attr({ src:stringArray[1]});
}
else
{
//上传出错
$("#divmsg").html("<img src=/images/note_error.gif />"+stringArray[2]+"");
}
$("#loading_msg").html("");
},
error:function (data, status, e)
{
alert("上传失败:"+e.toString());
}
});
return false;//.NET按钮控件取消提交
{
ajaxFileUpload("FileUpload1");
}
function ajaxFileUpload(obfile_id)
{
//准备提交处理
$("#loading_msg").html("<img src=/images/DotAjax.gif />");
//开始提交
$.ajax
({
type: "POST",
url:"ajaxUpFile.ashx",
data:"upfile="+$("#"+obfile_id).val(),
success:function (data, status)
{
//alert(data);
var stringArray = data.split("|");
if(stringArray[0]=="1")
{
//stringArray[0] 成功状态(1为成功,0为失败)
//stringArray[1] 上传成功的文件名
//stringArray[2] 消息提示
$("#divmsg").html("<img src=/images/note_ok.gif />"+stringArray[2]+" 文件地址:"+stringArray[1]);
$("#filepreview").attr({ src:stringArray[1]});
}
else
{
//上传出错
$("#divmsg").html("<img src=/images/note_error.gif />"+stringArray[2]+"");
}
$("#loading_msg").html("");
},
error:function (data, status, e)
{
alert("上传失败:"+e.toString());
}
});
return false;//.NET按钮控件取消提交
C#部分代码
1 /// <summary>
2 /// 上传文件 方法
3 /// </summary>
4 /// <param name="fileNamePath"></param>
5 /// <param name="toFilePath"></param>
6 /// <returns>返回上传处理结果 格式说明: 0|file.jpg|msg 成功状态|文件名|消息 </returns>
7 public string UpLoadFile(string fileNamePath, string toFilePath)
8 {
9 try
10 {
11 //获取要保存的文件信息
12 FileInfo file = new FileInfo(fileNamePath);
13 //获得文件扩展名
14 string fileNameExt = file.Extension;
15
16 //验证合法的文件
17 if (CheckFileExt(fileNameExt))
18 {
19 //生成将要保存的随机文件名
20 string fileName = GetFileName() + fileNameExt;
21 //检查保存的路径 是否有/结尾
22 if (toFilePath.EndsWith("/") == false) toFilePath = toFilePath + "/";
23
24 //按日期归类保存
25 string datePath = DateTime.Now.ToString("yyyyMM") + "/" + DateTime.Now.ToString("dd") + "/";
26 if (true)
27 {
28 toFilePath += datePath;
29 }
30
31 //获得要保存的文件路径
32 string serverFileName = toFilePath + fileName;
33 //物理完整路径
34 string toFileFullPath = HttpContext.Current.Server.MapPath(toFilePath);
35
36 //检查是否有该路径 没有就创建
37 if (!Directory.Exists(toFileFullPath))
38 {
39 Directory.CreateDirectory(toFileFullPath);
40 }
41
42 //将要保存的完整文件名
43 string toFile = toFileFullPath + fileName;
44
45 ///创建WebClient实例
46 WebClient myWebClient = new WebClient();
47 //设定windows网络安全认证 方法1
48 myWebClient.Credentials = CredentialCache.DefaultCredentials;
49 ////设定windows网络安全认证 方法2
50 //NetworkCredential cred = new NetworkCredential("UserName", "UserPWD");
51 //CredentialCache cache = new CredentialCache();
52 //cache.Add(new Uri("UploadPath"), "Basic", cred);
53 //myWebClient.Credentials = cache;
54
55 //要上传的文件
56 FileStream fs = new FileStream(fileNamePath, FileMode.Open, FileAccess.Read);
57 //FileStream fs = OpenFile();
58 BinaryReader r = new BinaryReader(fs);
59 //使用UploadFile方法可以用下面的格式
60 //myWebClient.UploadFile(toFile, "PUT",fileNamePath);
61 byte[] postArray = r.ReadBytes((int)fs.Length);
62 Stream postStream = myWebClient.OpenWrite(toFile, "PUT");
63 if (postStream.CanWrite)
64 {
65 postStream.Write(postArray, 0, postArray.Length);
66 }
67 else
68 {
69 return "0|" + serverFileName + "|" + "文件目前不可写";
70 }
71 postStream.Close();
72
73
74 return "1|" + serverFileName + "|" + "文件上传成功";
75 }
76 else
77 {
78 return "0|errorfile|" + "文件格式非法";
79 }
80 }
81 catch (Exception e)
82 {
83 return "0|errorfile|" + "文件上传失败,错误原因:" + e.Message;
84 }
85 }
2 /// 上传文件 方法
3 /// </summary>
4 /// <param name="fileNamePath"></param>
5 /// <param name="toFilePath"></param>
6 /// <returns>返回上传处理结果 格式说明: 0|file.jpg|msg 成功状态|文件名|消息 </returns>
7 public string UpLoadFile(string fileNamePath, string toFilePath)
8 {
9 try
10 {
11 //获取要保存的文件信息
12 FileInfo file = new FileInfo(fileNamePath);
13 //获得文件扩展名
14 string fileNameExt = file.Extension;
15
16 //验证合法的文件
17 if (CheckFileExt(fileNameExt))
18 {
19 //生成将要保存的随机文件名
20 string fileName = GetFileName() + fileNameExt;
21 //检查保存的路径 是否有/结尾
22 if (toFilePath.EndsWith("/") == false) toFilePath = toFilePath + "/";
23
24 //按日期归类保存
25 string datePath = DateTime.Now.ToString("yyyyMM") + "/" + DateTime.Now.ToString("dd") + "/";
26 if (true)
27 {
28 toFilePath += datePath;
29 }
30
31 //获得要保存的文件路径
32 string serverFileName = toFilePath + fileName;
33 //物理完整路径
34 string toFileFullPath = HttpContext.Current.Server.MapPath(toFilePath);
35
36 //检查是否有该路径 没有就创建
37 if (!Directory.Exists(toFileFullPath))
38 {
39 Directory.CreateDirectory(toFileFullPath);
40 }
41
42 //将要保存的完整文件名
43 string toFile = toFileFullPath + fileName;
44
45 ///创建WebClient实例
46 WebClient myWebClient = new WebClient();
47 //设定windows网络安全认证 方法1
48 myWebClient.Credentials = CredentialCache.DefaultCredentials;
49 ////设定windows网络安全认证 方法2
50 //NetworkCredential cred = new NetworkCredential("UserName", "UserPWD");
51 //CredentialCache cache = new CredentialCache();
52 //cache.Add(new Uri("UploadPath"), "Basic", cred);
53 //myWebClient.Credentials = cache;
54
55 //要上传的文件
56 FileStream fs = new FileStream(fileNamePath, FileMode.Open, FileAccess.Read);
57 //FileStream fs = OpenFile();
58 BinaryReader r = new BinaryReader(fs);
59 //使用UploadFile方法可以用下面的格式
60 //myWebClient.UploadFile(toFile, "PUT",fileNamePath);
61 byte[] postArray = r.ReadBytes((int)fs.Length);
62 Stream postStream = myWebClient.OpenWrite(toFile, "PUT");
63 if (postStream.CanWrite)
64 {
65 postStream.Write(postArray, 0, postArray.Length);
66 }
67 else
68 {
69 return "0|" + serverFileName + "|" + "文件目前不可写";
70 }
71 postStream.Close();
72
73
74 return "1|" + serverFileName + "|" + "文件上传成功";
75 }
76 else
77 {
78 return "0|errorfile|" + "文件格式非法";
79 }
80 }
81 catch (Exception e)
82 {
83 return "0|errorfile|" + "文件上传失败,错误原因:" + e.Message;
84 }
85 }