如果要向这个路劲下传文件,可以完全不需要知道WebBB/UpLoadFiles的物理路径。可以用下面的简单方法实现:
1.在WebBB项目下添加一个UploadHandler.ashx文件,代码如下:
C# codepublic class UploadHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
string filename = context.Request.QueryString["filename"].ToString();
using (FileStream inputStram = File.Create(context.Server.MapPath("UpLoadFiles/") + filename))
{
SaveFile(context.Request.InputStream, inputStram);
}
}
protected void SaveFile(Stream stream, FileStream inputStream)
{
int bufSize=1024;
int byteGet=0;
byte[] buf=new byte[bufSize];
while ((byteGet = stream.Read(buf, 0, bufSize)) > 0)
{
inputStream.Write(buf, 0, byteGet);
}
}
public bool IsReusable
{
get
{
return false;
}
}
}
2.这样你就有了一个上传路径为http://xxxxxxxx/WebBB/UploadHandler.ashx
在WebAA项目中通过WebClient或者WebRequest请求该url,下面以WebClient为例说明。
在WebAA中新建test.aspx页面,上面有FileUpload控件FileUpload1和Button控件Button1,具体事件代码如下:
C# code
using System.IO;
using System.Net;
MemoryStream ms;
protected void wc_OpenWriteCompleted(object sender, OpenWriteCompletedEventArgs e)
{
int bufSize = 10;
int byteGet = 0;
byte[] buf = new byte[bufSize];
while ((byteGet = ms.Read(buf, 0, bufSize)) > 0)//循环读取,上传
{
e.Result.Write(buf, 0, byteGet);//注意这里
}
e.Result.Close();//关闭
ms.Close();关闭ms
}
protected void Button1_Click(object sender, EventArgs e)
{
FileUpload fi = FileUpload1;
byte[] bt = fi.FileBytes;//获取文件的Byte[]
ms = new MemoryStream(bt);//用Byte[],实例化ms
UriBuilder url = new UriBuilder("http://xxxxxxxx/WebBB/UploadHandler.ashx");//上传路径
url.Query = string.Format("filename={0}", Path.GetFileName(fi.FileName));//上传url参数
WebClient wc = new WebClient();
wc.OpenWriteCompleted += new OpenWriteCompletedEventHandler(wc_OpenWriteCompleted);//委托异步上传事件
wc.OpenWriteAsync(url.Uri);//开始异步上传
}