日期:2014-05-18  浏览次数:20503 次

ajax 图片上传
我现在要用ajax做一个上传图片的方法
现在在后我已经写好了上传的方法。但是在前台我不知道怎么获取图片的对象到后台,(request.files)获取不到这个值
看了网上有通过框架做的,但是我一直不明白原理,
想问下:怎么用ajax或js的方法将file的图片对象传递到后台

------解决方案--------------------
C# code
/// <summary> 
/// 上传图片 c# 
/// </summary> 
/// <param name= "fileNamePath "> 文件路径 </param> 
/// <param name= "uriString "> 保存路径 </param> 
/// using System.IO; 
/// using System.Net; 
private void UpLoadFile(string fileNamePath,string uriString)  
{  
string fileName = fileNamePath.Substring(fileNamePath.LastIndexOf( "\\ ") + 1);  
string NewFileName = DateTime.Now.ToString( "yyMMddhhmmss ") + DateTime.Now.Millisecond.ToString() + fileNamePath.Substring(fileNamePath.LastIndexOf( ". "));  
   
string fileNameExt = fileName.Substring(fileName.LastIndexOf( ". ") + 1);  
if(uriString.EndsWith( "/ ") == false) uriString = uriString + "/ ";  
   
uriString = uriString + NewFileName;  
/// 创建WebClient实例  
WebClient myWebClient = new WebClient();  
myWebClient.Credentials = CredentialCache.DefaultCredentials;  
   
// 要上传的文件  
// FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);  
FileStream fs = new FileStream(fileNamePath, FileMode.Open, FileAccess.Read);  
//FileStream fs = OpenFile();  
BinaryReader r = new BinaryReader(fs);  
// try  
// {  
//使用UploadFile方法可以用下面的格式  
//myWebClient.UploadFile(uriString, "PUT ",fileNamePath);  
byte[] postArray = r.ReadBytes((int)fs.Length);  
Stream postStream = myWebClient.OpenWrite(uriString, "PUT ");  
if(postStream.CanWrite)  
{  
postStream.Write(postArray,0,postArray.Length);  
}  
else  
{  
Response.Write( "文件目前不可写! ");  
}  
postStream.Close();  
  
}