JQUERY+ASP.NET的AJAX文件上传

JQUERY+ASP.NET的AJAX文件上传
2009/04/24 23:31

 

在知道JQUREY和微软集成的消息后,在项目里面就开始尽量使用JQUERY了,这个DEMO是一个示例。主要文件两个:

ajaxUpFile.ashx     服务端处理

Default.aspx     用户提交

下面贴出主要代码:

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按钮控件取消提交
}


C#代码部分:

 

/// <summary>
        
/// 上传文件 方法
        
/// </summary>
        
/// <param name="fileNamePath"></param>
        
/// <param name="toFilePath"></param>
        
/// <returns>返回上传处理结果   格式说明: 0|file.jpg|msg   成功状态|文件名|消息    </returns>
        public string UpLoadFile(string fileNamePath, string toFilePath)
         {
            
try
             {
                
//获取要保存的文件信息
                 FileInfo file = new FileInfo(fileNamePath);
                
//获得文件扩展名
                string fileNameExt = file.Extension;

                
//验证合法的文件
                if (CheckFileExt(fileNameExt))
                 {
                    
//生成将要保存的随机文件名
                    string fileName = GetFileName() + fileNameExt;
                    
//检查保存的路径 是否有/结尾
                    if (toFilePath.EndsWith("/") == false) toFilePath = toFilePath + "/";

                    
//按日期归类保存
                    string datePath = DateTime.Now.ToString("yyyyMM") + "/" + DateTime.Now.ToString("dd") + "/";
                    
if (true)
                     {
                         toFilePath
+= datePath;
                     }

                    
//获得要保存的文件路径
                    string serverFileName = toFilePath + fileName;
                    
//物理完整路径                    
                    string toFileFullPath = HttpContext.Current.Server.MapPath(toFilePath);
                    
                    
//检查是否有该路径   没有就创建
                    if (!Directory.Exists(toFileFullPath))
                     {
                         Directory.CreateDirectory(toFileFullPath);
                     }

                    
//将要保存的完整文件名                
                    string toFile = toFileFullPath + fileName;

                    
///创建WebClient实例      
                     WebClient myWebClient = new WebClient();
                    
//设定windows网络安全认证   方法1
                     myWebClient.Credentials = CredentialCache.DefaultCredentials;
                    
////设定windows网络安全认证   方法2
                    //NetworkCredential cred = new NetworkCredential("UserName", "UserPWD");
                    
//CredentialCache cache = new CredentialCache();
                    
//cache.Add(new Uri("UploadPath"), "Basic", cred);
                    
//myWebClient.Credentials = cache;

                    
//要上传的文件      
                     FileStream fs = new FileStream(fileNamePath, FileMode.Open, FileAccess.Read);
                    
//FileStream fs = OpenFile();      
                     BinaryReader r = new BinaryReader(fs);
                    
//使用UploadFile方法可以用下面的格式      
                    
//myWebClient.UploadFile(toFile, "PUT",fileNamePath);      
                    byte[] postArray = r.ReadBytes((int)fs.Length);
                     Stream postStream
= myWebClient.OpenWrite(toFile, "PUT");
                    
if (postStream.CanWrite)
                     {
                         postStream.Write(postArray,
0, postArray.Length);
                     }
                    
else
                     {
                        
return "0|" + serverFileName + "|" + "文件目前不可写";
                     }
                     postStream.Close();


                    
return "1|" + serverFileName + "|" + "文件上传成功";
                 }
                
else
                 {
                    
return "0|errorfile|" + "文件格式非法";
                 }
             }
            
catch (Exception e)
             {
                
return "0|errorfile|" + "文件上传失败,错误原因:" + e.Message;
             }
         }

 

ajaxUpFile.ashx     服务端处理

Default.aspx     用户提交

下面贴出主要代码:

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按钮控件取消提交
}

 

你可能感兴趣的:(asp.net)