ASP.NET,AJAX文件上传的疑问
原本以为用这种方式,把此方法放到一个Httphandler中,然后从JAVASCRIPT访问Httphandler来实现无刷新的文件上传。没想到,这样同样是不行的,只能在本机测试通过,如果放到网上,或者从其他地方访问就会提示无法找到文件,可见在ASP.NET中它只能用于上传服务器端的文件。
之前在网站也搜索到一篇文章是写怎么在Httphandler中来实现文件上传的,是国外的一个BLOG,没怎么看明白,貌似还借助于一个applet。后来由于没资源我也没去试过那方法到底是否可行了。
我现在还真的不知道在ASP.NET怎么能够纯手工的实现AJAX的无刷新上传文件,因为从JavaScript从提交表单访问Httphandler,在里面根本无法获取到表单的信息,HttpFileCollection,HttpPostedFile,里面都是空的。我觉得ASP.NET中的Httphandler与JSP中的Serverlet到有一些相似之处,可是在JSP中用Serverlet来实现一个AJAX无刷新上传很容易,现在真的有点困惑了,难道ASP.NET要实现无刷新的上传一定得要用UpdatePanel。都不知道.NET到什么都封装到控件,我们只能无脑的拖出来使用,就不能像JSP一样,多让我们程序员按照自己的思路去实现一个东西。
private void Uploadfile(string filepath)
{
//string filepath = Request["filepath"].ToString();
Response.ContentType = "text/plain";
if (filepath == "" || filepath == null)
{
return;
}
else
{
FileStream fs=null;
BinaryReader br=null;
Stream postStream=null;
//use a try-catch to catch an exception if happened
try
{
//Get a filestream form the file
fs = new FileStream(filepath, FileMode.Open, FileAccess.Read);
//Create a binaryreader object for read the filestream which you can deliver an parmetter filestream
br = new BinaryReader(fs);
//Create a webclient for send data or receive data from uri
WebClient myWebClient = new WebClient();
//Get the file name from parm filepath
string filename = filepath.Substring(filepath.LastIndexOf("//") + 1);
//Get server path
string tofilepath = Server.MapPath("~/uploadFiles/" + filename);
//Get the windows safety credential
myWebClient.Credentials = CredentialCache.DefaultCredentials;
byte[] postArr = br.ReadBytes((int)fs.Length);
postStream = myWebClient.OpenWrite(tofilepath, "PUT");
if (postStream.CanWrite)
{
postStream.Write(postArr, 0, postArr.Length);
Response.Write("File upload successfully !");
}
else
{
Response.Write("File can not be writed !");
}
}
catch (Exception ex)
{
Response.Write("File upload failed the reason is :" + ex.Message);
}
finally
{
if(postStream!=null)
postStream.Close();
if(br!=null)
br.Close();
if(fs!=null)
fs.Close();
Response.End();
}
}
}