ASP.NET跨伺服器上傳檔案的相關解決方案

來源:互聯網
上載者:User

標籤:des   style   http   color   io   os   ar   strong   for   

第一種:通過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跨伺服器上傳檔案的相關解決方案

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.