Asp. NET cross-server upload files related solutions

Source: Internet
Author: User

The first type: uploading Files via FTP

First, set up the FTP service on another server and create a user and password that allow uploading, and then upload the file directly to the FTP server in ASP. The code is as follows:

<%@ 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)
{
The FTP server address to receive the file
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;

User names and passwords that are allowed to be uploaded on the FTP server
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>
<title> How to upload a file to another server two </title>
<body>
<form id= "Form1" runat= "Server" >
<asp:fileupload id= "FileUpload1" runat= "Server"/>
<asp:button id= "Button1" runat= "Server" onclick= "button1_click" text= "Upload file"/>
<div><asp:label id= "Label1" runat= "Server" text= "" ></asp:Label></div>
</form>
</body>

The second type: uploading Files via WebClient

For example: Now the virtual directory of the Web application being developed is Webaa, and the virtual directory of the other application is WEBBB, now to save the picture from Webaa to a uploadfiles folder under WEBBB

1. Add a uploadhandler.ashx file under the WEBBB project with the following code:

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. In the WEBAA project, request the URL by WebClient or WebRequest, as shown in the WebClient example below. Create a new test.aspx page in Webaa with the FileUpload control FileUpload1 and the button control Button1, with the following event 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)//loop read, upload     {        e.result.write (buf, 0, byteget);//Note here &N Bsp  }    e.result.close ();//close     Ms. Close (); ms}protected void Button1_Click (object sender, EventArgs e) {    FileUpload fi = fileupload1; & nbsp   byte[] bt = fi. filebytes;//Get file byte[]    ms = new MemoryStream (BT);//byte[], instantiate ms     uribuilder url = new Ur Ibuilder ("Http://xxxxxxxx/WebBB/UploadHandler.ashx");//upload path     URL. Query = string. Format ("filename={0}", Path.getfilename (FI. FileName);//upload URL parameter     WebClient WC = new WebClient ();    WC. openwritecompleted + = new OpenwritecompletedeventHandler (wc_openwritecompleted);//delegate asynchronous upload event     WC. OpenWriteAsync (URL. URI);//start Asynchronous upload}

The third type: uploading Files via Web service (in the same way as the second principle)

1. First define the Web service class with the following code:

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 description    //</summary>    [We bservice (Namespace = "http://tempuri.org/")]    [webservicebinding (ConformsTo = wsiprofiles.basicprofile1_ 1)]    [ToolboxItem (false)]    public class updownfile:system.web.services.webservice    {       //upload files to WebService server, here in order to manipulate the method, the files are saved in the file directory under the Updownfile Service folder         [webmethod]        public bool Up (byte[] data, string filename)       &NBS P {            try            {        &NBSP ;       FileStream fs = File.create (Server.mappatH ("file/") + filename);                FS. Write (data, 0, data. Length);                FS. Close ();                return true;           }&NB Sp           catch            {          &NBS P     return false;           }       }     &NB Sp  //Download the WebService file on the server         [webmethod]        public byte[] down (ST Ring filename)         {            String filepath = Server.MapPath ("Fil e/") + filename;            if (file.exists (filepath))           &NB Sp {                try      &NBSP         {                    FileStream s = file.ope Nread (filepath);                    return Convertstreamtobytebuffer (s) ;               }                CATCH&NB Sp               {                    RE Turn new byte[0];               }           }&NBSP ;           else            {          &NBSP ;     return new byte[0];           }       }   }}

2. Refer to the Web service created above in the website, named (Updownfile, you can define it yourself), then implement the file upload and download separately in page downfile.aspx:

Upload:

FileUpload1 is an fileupload control for an ASPX page
Updownfile.updownfile up = new Updownfile.updownfile ();
Up. Up (Convertstreamtobytebuffer (FileUpload1.PostedFile.InputStream),
FileUpload1.PostedFile.FileName.Substring (FileUpload1.PostedFile.FileName.LastIndexOf ("\ \") + 1));

Download:
Updownfile.updownfile down = new Updownfile.updownfile ();
byte[] File = down. Down (request.querystring["filename"]. ToString ()); FileName is the path to the file you want to download, and you can get the file path yourself in other ways
Response.BinaryWrite (file);

The following is a function that converts a file to a file byte (because the stream type is not transmitted directly through WebService):

Protected byte[] Convertstreamtobytebuffer (stream s) {BinaryReader br = new BinaryReader (stream); byte[] Filebytes = br. Readbytes ((int) stream.    Length); return filebytes;}

Fourth: How to jump through pages or nested pages (this method is very simple, strictly not cross-server, and has certain limitations)

Implementation method:

1. On the page that needs to upload the file, add Iframe,iframe address to another server upload page, and the page must include the upload button;
2. Need to upload the use of JS location.href or server Response.Redirect to jump to another page upload;

Methods in fact, there are not one by one cases, of course, the above method is only to implement upload and download functions, and sometimes may also need to consider cross-server delete files, this may need to consider security and other aspects of the problem.

Sync posted on my personal site: http://www.zuowenjun.cn/post/2014/09/29/44.html

Asp. NET cross-server upload files related solutions

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.