[ 来源:http://www.it55.com | 作者: | 时间:2007-10-30 | 收藏 | 推荐 ] 【大 中 小】
今天,我们来看看,如何使用WebClient的Postdata实现跨网站文件上传功能
先看这个图:

A 层是我们的用户表单,如一个简单的修改用户信息页面
B 层也是一个网站,它是一个上传功能。
C 层是存放文件的服务器
B网站可以是一台独立的网站服务器,它做的事情就只是上传,并处理文件,如:切割图片、锐化图片等功能。当A网站需要上传功能时,就可以通过一个iframe去调用B网站的上传页面,两者之间通过JS的Parent来传递数据(具体做法请看我以前写的《》)。
但今天有个功能却不能用这种方式做,不能使用iframe,所以一直想了好几个办法,最终做了一个通过WebClient来将文件数据POST到B服务器,B服务器再处理,并保存。这种做法虽然效果没有达到完全的分离(上传时A网站还是要将文件信息从用户的本地读到A网站的服务器),不过处理文件的资源已经分开了,速度上面应该会有些好的(看具体情况了,我这里会将文件缩小并切割成好几种不同大小的格式,再将切割完成的图进行锐化处理)。
我一直在想,怎么才能将Ajax一样,直接把信息POST到B网站的一个页面上,终于找到WebClient,我先把文件读成Byte数组,再用WebClient提交到B服务器的页面上,B服务接收此信息并转成一个Image,然后处理文件并保存,最后返回结果。
再看一下具体的代码:
A层页面代码的Default.aspx:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>上传文件端</title>
</head>
<body>
<form id="form1" runat="server">
<asp:FileUpload ID="file1" runat="server" /> <asp:Button ID="btnPost" runat="server" Text="上传" OnClick="btnPost_Click" />
</form>
</body>
</html>
A层服务端代码 Default.aspx.cs
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnPost_Click(object sender, EventArgs e)
{
if(! file1.HasFile)
{
Alert("还未选择要上传的文件.");
return;
}
HttpPostedFile myFile = file1.PostedFile;
string result = "";
try
{
//将文件转换成字节形式
byte[] fileByte = new byte[myFile.InputStream.Length];
myFile.InputStream.Read(fileByte, 0, fileByte.Length);
//通过WebClient类来提交文件数据
//定义提交URL地址,它会接收文件的字节数据,并保存,再返回相应的结果[此处具体用的时候要修改]
string postUrl = "http://localhost:2956/Upload/uploadpic.aspx?oldfilename=" + myFile.FileName;
System.Net.WebClient webClient = new System.Net.WebClient();
byte[] responseArray = webClient.UploadData(postUrl, "POST", fileByte);
//将返回的字节数据转成字符串(也就是uploadpic.aspx里面的页面输出内容)
result = System.Text.Encoding.Default.GetString(responseArray, 0, responseArray.Length);
(编辑:IT资讯之家 www.it55.com)