ASP. NET cross-Server File Upload solutions, asp.net File Upload

Source: Internet
Author: User

ASP. NET cross-Server File Upload solutions, asp.net File Upload

First: upload files through FTP

First, set the FTP service on another server and create the user and password that can be uploaded. Then, in ASP. you can directly upload files to this FTP server. 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 button#click (object sender, EventArgs e)
{
// The ftp server address for receiving files
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;

// The user name and password that can 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>
<Html xmlns = "http://www.w3.org/1999/xhtml">
<Head runat = "server">
<Title> method 2 of uploading a file to another server </title>
</Head>
<Body>
<Form id = "form1" runat = "server">
<Asp: FileUpload ID = "FileUpload1" runat = "server"/>
<Asp: Button ID = "Button1" runat = "server" OnClick = "button#click" Text = "Upload File"/>
<Div> <asp: Label ID = "Label1" runat = "server" Text = ""> </asp: Label> </div>
</Form>
</Body>
</Html>

Type 2: Use WebClient to upload files

For example, the virtual directory of the developed web application is WebAA, and the virtual directory of the other application is WebBB. Now we need to save the image from WebAA to an UpLoadFiles folder under WebBB.

1. Add an UploadHandler. ashx file under the WebBB project. The Code is as follows:

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. Request the url through WebClient or WebRequest in the WebAA project. The following uses WebClient as an example. Create the test. aspx page in WebAA with the FileUpload control FileUpload1 and Button control Button1 on it. The specific event code is as follows:

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) // Read cyclically, upload {e. result. write (buf, 0, byteGet); // note here} e. result. close (); // Close ms. close (); Close ms} protected void Button1_Click (object sender, EventArgs e) {FileUpload fi = FileUpload1; byte [] bt = fi. fileBytes; // get the object's Byte [] ms = new MemoryStream (bt); // instantiate ms UriBuilder url = new UriBuilder (" http://xxxxxxxx/WebBB/UploadHandler.ashx "); // Url of the upload path. 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}

Third: upload files through Web Service (which is somewhat the same as the second method)

1. First define the Web Service class. The Code is as follows:

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> // summary of UpDownFile /// </summary> [WebService (Namespace =" http://tempuri.org/ ")] [WebServiceBinding (ConformsTo = WsiProfiles. basicProfile1_1)] [ToolboxItem (false)] public class UpDownFile: System. web. services. webService {// Method for uploading files to the server where WebService is located, all files are saved in the [WebMethod] public bool Up (byte [] data, string filename) {try {FileStream fs = File in the File directory where the UpDownFile service is located. create (Server. mapPath ("File/") + filename); fs. write (data, 0, data. length); fs. close (); return true;} catch {return false;} // Method for downloading files on the server where WebService is located [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. reference the WEB Service created above in the website and name it (UpDownFile, which can be customized). Then, upload and download files on the DownFile. aspx page respectively:

Upload:

// FileUpload1 is a FileUpload control of the 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 file path to be downloaded. You can obtain the file path in other ways.
Response. BinaryWrite (file );

The following is a function for converting a file to a file byte (because Stream type cannot be transmitted directly through WebService ):

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

Method 4: Jump to or nest a page through a page (this method is very simple, not cross-server strictly, and has certain limitations)

Implementation Method:

1. Add iframe to the page for file upload. The iframe address points to the upload page of another server, and the page must contain the upload button;
2. Use JS location. href or server-side Response. redirect to jump to another Server Upload page;

There are actually many methods. Here we will not illustrate them one by one. Of course, the above method only implements the upload and download functions, and sometimes you may need to consider cross-Server File Deletion, security issues may need to be considered.

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


ASPNET (c #) Cross-Server File Upload

Sssssss
 
Aspnet uploads files to the specified folder on the server

Protected void button#click (object sender, EventArgs e)
{
// Upload and display the Avatar
If (this. File1.PostedFile. ContentLength! = 0)
{
If (File1.Value! = "")
{
String strfile = this. File1.PostedFile. FileName; // obtain the complete file path, including the file name.
// String strfile = this. File1.Filename; // obtain the uploaded file name.
Int filepos = strfile. LastIndexOf ("."); // get the suffix
String strfilename = strfile. Substring (filepos); // truncate the suffix
String time1 = System. DateTime. Now. ToString ("yyyyMMddHHmmssffff"); // obtain the time
String filesavepath = Server. MapPath ("a") + "\" + time1 + strfilename; // saved path and file name, suffix

This. File1.PostedFile. SaveAs (filesavepath );
// Image1.Src = filesavepath; // file name
Image1.Src = "a" + "\" + time1 + strfilename; // http File Name
Response. Write (filesavepath );
}
}

This is the code for uploading images.
However, the file you want to upload is similar to this one.
You need to try it yourself.

The following code is required:
Protected void button#click (object sender, EventArgs e)
{

Try
{
If (FileUpload1.PostedFile. FileName = "")
{
Response. Write ("<script language = javascript> alert ('the uploaded file cannot be blank !! ') </Script> ");
Return;
... The remaining full text>

Related Article

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.