ASP. NET Upload file

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 voidButton1_Click (Objectsender, EventArgs e) {    //the FTP server address to receive the fileString 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 serverRequest. Credentials =NewNetworkCredential ("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>"http://www.w3.org/1999/xhtml">"Server"><title> How to upload a file to another server two </title>"Form1"runat="Server"><asp:fileupload id="FileUpload1"runat="Server"/><asp:button id="Button1"runat="Server"onclick="Button1_Click"text="Uploading Files"/><div><asp:label id="Label1"runat="Server"text=""></asp:Label></div></form></body>Code

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 classuploadhandler:ihttphandler{ Public voidProcessRequest (HttpContext context) {stringfilename = context. request.querystring["filename"].        ToString (); using(FileStream Inputstram = file.create (context.) Server.MapPath ("uploadfiles/") +filename)) {SaveFile (context.        Request.inputstream, Inputstram); }    }    protected voidSaveFile (Stream stream, FileStream inputstream) {intBufsize=1024x768;intbyteget=0;byte[] buf=New byte[bufSize]; while((Byteget = stream.) Read (BUF,0, bufSize)) >0) {inputstream.write (buf,0, Byteget);}} Public BOOLisreusable{Get{return false;}}} 
Code

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:

usingSystem.IO;usingSystem.Net; MemoryStream MS;protected voidWc_openwritecompleted (Objectsender, OpenWriteCompletedEventArgs e) {    intBufSize =Ten; intByteget =0; byte[] buf =New byte[BufSize];  while(Byteget = Ms. Read (BUF,0, bufSize)) >0)//loop read, upload{e.result.write (buf,0, Byteget);//Watch this .} e.result.close ();//CloseMs. Close (); Turn off Ms}protected voidButton1_Click (Objectsender, EventArgs e) {FileUpload fi=FileUpload1; byte[] bt = fi. Filebytes;//get the file byte[]ms =NewMemoryStream (BT);//using byte[], instantiate Msuribuilder URL=NewUriBuilder ("http://xxxxxxxx/WebBB/UploadHandler.ashx");//Upload PathUrl. Query =string. Format ("filename={0}", Path.getfilename (FI. FileName));//Upload URL ParametersWebClient WC =NewWebClient (); Wc. Openwritecompleted+=NewOpenwritecompletedeventhandler (wc_openwritecompleted);//delegate asynchronous upload eventWc. OpenWriteAsync (URL. Uri);//Start Asynchronous Upload}
Code

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:

usingSystem;usingSystem.Data;usingsystem.web;usingSystem.Collections;usingSystem.Web.Services;usingSystem.Web.Services.Protocols;usingSystem.ComponentModel;usingSystem.IO;namespaceupdownfile{/**/    /// <summary>    ///Summary description of Updownfile/// </summary>[WebService (Namespace ="http://tempuri.org/")] [WebServiceBinding (ConformsTo=Wsiprofiles.basicprofile1_1)] [ToolboxItem (false)]     Public classUpDownFile:System.Web.Services.WebService {//how to upload files to WebService server, where the files are stored in the file directory under the folder where the Updownfile service is located in order to operate the method[WebMethod] Public BOOLUp (byte[] Data,stringfilename) {            Try{FileStream fs= File.create (Server.MapPath ("file/") +filename); Fs. Write (data,0, data.                Length); Fs.                Close (); return true; }            Catch            {                return false; }        }         //ways to download files on the WebService server[WebMethod] Public byte[] Down (stringfilename) {            stringfilepath = Server.MapPath ("file/") +filename; if(File.exists (filepath)) {Try{FileStream s=File.openread (filepath); returnConvertstreamtobytebuffer (s); }                Catch                {                    return New byte[0]; }            }            Else            {                return New byte[0]; }        }    }}
Code

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 pageUpdownfile.updownfile up =NewUpdownfile.updownfile (); Up. Up (Convertstreamtobytebuffer (FileUpload1.PostedFile.InputStream), FileUpload1.PostedFile.FileName.Substring (Fil EUpload1.PostedFile.FileName.LastIndexOf ("\\") +1); Download: Updownfile.updownfile down=NewUpdownfile.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 waysresponse.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=NewBinaryReader (stream); byte[] filebytes = Br. Readbytes ((int) stream.    Length); returnfilebytes;}
Code

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;

ASP. NET Upload file

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.