第一种:通过FTP来上传文件

首先,在另外一台服务器上设置好FTP服务,并创建好允许上传的用户和密码,然后,在ASP.NET里就可以直接将文件上传到这台 FTP 服务器上了。代码如下:

<%@ Page Language="C#" EnableViewState="false"%>

<%@ Import Namespace="System.Net" %>
<%@ Import Namespace="System.IO" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
  protected void Button1_Click(object sender, EventArgs e)
  {
    //要接收文件的 ftp 服务器地址
    String serverUri = "ftp://192.168.3.1/";
    String fileName = Path.GetFileName(FileUpload1.FileName);
    serverUri += fileName;

FtpWebRequest request = (FtpWebRequest)WebRequest.Create(serverUri);
request.Method = WebRequestMethods.Ftp.AppendFile;
request.UseBinary = true;
request.UsePassive = true;

// ftp 服务器上允许上传的用户名和密码
request.Credentials = new NetworkCredential("upload", "upload");
Stream requestStream = request.GetRequestStream();
Byte[] buffer = FileUpload1.FileBytes;

requestStream.Write(buffer, 0, buffer.Length);
requestStream.Close();
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
Label1.Text = response.StatusDescription;
response.Close();
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>将文件上传到另外一个服务器的方法二</title>
</head>
<body>
<form id="form1" runat="server">
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="上传文件" />
<div><asp:Label ID="Label1" runat="server" Text=""></asp:Label></div>
</form>
</body>
</html> 

第二种:通过WebClient来上传文件

如:现在的开发的web应用程序的虚拟目录是WebAA,另一个应用程序的虚拟目录是WebBB,现在要从WebAA向WebBB下的一个UpLoadFiles文件夹下保存图片

1.在WebBB项目下添加一个UploadHandler.ashx文件,代码如下:

public 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.在WebAA项目中通过WebClient或者WebRequest请求该url,下面以WebClient为例说明。 在WebAA中新建test.aspx页面,上面有FileUpload控件FileUpload1和Button控件Button1,具体事件代码如下:

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);//开始异步上传
}

第三种:通过Web Service来上传文件(与第二种其实原理有些相同)

1.首先定义Web Service类,代码如下:

using System;
using System.Data;
using System.Web;
using System.Collections;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.ComponentModel;
using System.IO;
 
namespace UpDownFile
{
    /**/
    /// <summary>
    /// UpDownFile 的摘要说明
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [ToolboxItem(false)]
    public class UpDownFile : System.Web.Services.WebService
    {
        //上传文件至WebService所在服务器的方法,这里为了操作方法,文件都保存在UpDownFile服务所在文件夹下的File目录中
        [WebMethod]
        public bool Up(byte[] data, string filename)
        {
            try
            {
                FileStream fs = File.Create(Server.MapPath("File/") + filename);
                fs.Write(data, 0, data.Length);
                fs.Close();
                return true;
            }
            catch
            {
                return false;
            }
        }
 
        //下载WebService所在服务器上的文件的方法
        [WebMethod]
        public byte[] Down(string filename)
        {
            string filepath = Server.MapPath("File/") + filename;
            if (File.Exists(filepath))
            {
                try
                {
                    FileStream s = File.OpenRead(filepath);
                    return ConvertStreamToByteBuffer(s);
                }
                catch
                {
                    return new byte[0];
                }
            }
            else
            {
                return new byte[0];
            }
        }
    }
}

2.在网站中引用上述创建的WEB服务,命名为(UpDownFile,可自行定义),然后在页面DownFile.aspx中分别实现文件上传与下载:

上传:

 

//FileUpload1是aspx页面的一个FileUpload控件
            UpDownFile.UpDownFile up = new UpDownFile.UpDownFile();
            up.Up(ConvertStreamToByteBuffer(FileUpload1.PostedFile.InputStream),
            FileUpload1.PostedFile.FileName.Substring(FileUpload1.PostedFile.FileName.LastIndexOf("\\") + 1));

下载:
            UpDownFile.UpDownFile down = new UpDownFile.UpDownFile();
            byte[] file = down.Down(Request.QueryString["filename"].ToString()); //filename是要下载的文件路径,可自行以其它方式获取文件路径
            Response.BinaryWrite(file);

以下是将文件流转换成文件字节的函数(因为Stream类型的是不能直接通过WebService传输):

 protected byte[] ConvertStreamToByteBuffer(Stream s)
 {
    BinaryReader br = new BinaryReader(stream);
    byte[] fileBytes = br.ReadBytes((int)stream.Length);
    return fileBytes;
}

第四种:通过页面跳转或嵌套页面的方式(这种方法很简单,严格不算跨服务器,且有一定的局限性)

实现方法:

1.在需要上传文件的页面加入iframe,iframe的地址指向另一个服务器上传页面,并且页面需包含上传按钮;
2.需要上传时就利用JS的location.href或服务端的Response.redirect跳转至另一个服务器上传页面;

方法其实还有多很,这里就不一一例举,当然上述方法只是实现上传与下载功能,有时可能还需考虑跨服务器删除文件,这个可能需要考虑安全等方面的问题。

同步发表于我的个人网站:http://www.zuowenjun.cn/post/2014/09/29/44.html

ASP.NET跨服务器上传文件的相关解决方案的更多相关文章

  1. 关于nutz跨服务器上传文件

    关于nutz跨服务器上传文件  发布于 578天前  作者 yong9664  770 次浏览  复制  上一个帖子  下一个帖子  标签: 无 是这样的,项目在一台服务器,文件要存储到另外一台服务器 ...

  2. idea 内置tomcat jersey 跨服务器 上传文件报400错误

    报错内容 com.sun.jersey.api.client.UniformInterfaceException: PUT http://.jpg returned a response status ...

  3. asp.net跨域上传文件

    前端: <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" con ...

  4. jersey实现跨服务器上传

    1.导入跨服务器上传文件jar文件 <dependency> <groupId>commons-io</groupId> <artifactId>com ...

  5. 阶段3 3.SpringMVC·_05.文件上传_5 文件上传之跨服务器上传分析和搭建环境

    使用这个jar包来跨服务器上传 搞两个tomcat.一个springmvc一个fileupload 选中tomcat server点击左边的加号 需要改端口和JMX pport这个端口 部署文件上传的 ...

  6. xshell终端向远程服务器上传文件方法

    centos-7下在本地终端里向远程服务器上传文件,在命令行中执行的软件. 安装命令如下: 在终端里输入如下命令: 会弹出如下窗口 选择你要上传的文件即可上传成功.

  7. 前端AngularJS后端ASP.NET Web API上传文件

    本篇体验使用AngularJS向后端ASP.NET API控制器上传文件.    首先服务端: public class FilesController : ApiController { //usi ...

  8. asp.net限制了上传文件大小为..M,解决方法

    asp.net限制了上传文件大小为4M,在:在web.config里加下面一句,加在<System.web></System.web>之间如下:<system.web&g ...

  9. Java模拟客户端向服务器上传文件

    先来了解一下客户端与服务器Tcp通信的基本步骤: 服务器端先启动,然后启动客户端向服务器端发送数据. 服务器端收到客户端发送的数据,服务器端会响应应客户端,向客户端发送响应结果. 客户端读取服务器发送 ...

随机推荐

  1. 解决ASP.NET在IE10中Session丢失问题【转】

    今天发现在IE10中登录我公司的一个网站时,点击其它菜单,页面总会自动重新退出到登录页,后检查发现,IE10送出的HTTP头,和.AUTH Cookie都没问题,但使用表单验证机制(FormsAuth ...

  2. github host你懂得,如果你是程序员请不要乱传,求求了

    可用截止测试时间 2015-01-12 github相关的hosts 207.97.227.239 github.com 65.74.177.129 www.github.com 207.97.227 ...

  3. HTTP基本认证(Basic Authentication)的JAVA示例

    大家在登录网站的时候,大部分时候是通过一个表单提交登录信息.但是有时候浏览器会弹出一个登录验证的对话框,如下图,这就是使用HTTP基本认证.下面来看看一看这个认证的工作过程:第一步:  客户端发送ht ...

  4. Qt 调试时的错误——Debug Assertion Failed!

    在VS2008中写qt程序时调试出现此问题,但在release模式下就不存在,在网上搜罗了一圈,是指针的问题. 问题是这样的: 需要打开两个文件,文件中数据类型是float,我使用QVector进行保 ...

  5. Halcon学习标定助手

    本文采用halcon标定助手进行标定. 第一步:打开标定助手. 第二步:对描述文件进行修改 具体:打开算子窗口,输入gen_caltab,进行描述文件修改. 参数XNum和YNum为7行*7列的圆,M ...

  6. Codeforces Round #292 (Div. 1) C. Drazil and Park 线段树

    C. Drazil and Park 题目连接: http://codeforces.com/contest/516/problem/C Description Drazil is a monkey. ...

  7. 每日英语:What To Expect To Wear When You're Expecting

    AT THE ACADEMY AWARDS earlier this month, Kerry Washington, the star of the ABC-TV series 'Scandal,' ...

  8. Transaction recovery: lock conflict caught and ignored

    Transaction recovery: lock conflict caught and ignored环境:RAC 4节点.oracle 11.2.0.4.redhat 5.9 64bit 问题 ...

  9. IIS服务器下做301永久重定向设置方法

    实现方法如下: 1.新建一个站点,对应目录如E:\wwwroot\301web.该目录下只需要1个文件,即index.html或者加个404.htm.绑定要跳转的域名,如图: 2.在IIS中选中刚才我 ...

  10. [GraphQL] Write a GraphQL Schema in JavaScript

    Writing out a GraphQL Schema in the common GraphQL Language can work for simple GraphQL Schemas, but ...