C # implement file upload/download from URL

Source: Internet
Author: User

File Upload

1. In form, set enctype to "multipart/form-Data ":
<Form ID = "webform3" method = "Post" enctype = "multipart/form-Data" runat = "server">

2. Determine whether a file has been uploaded:
When
The user does not select any file to be uploaded. That is, when the text box in the htmlinputfile control is empty, the user clicks the upload button and obtains the file1.postedfile pair
Objects are not null, so they cannot be used (file1.postedfile =
Null) to determine whether a file has been uploaded. Use (file1.postedfile. contentlength! = 0 ).

Iii. Determine the mimie type of the uploaded file:
After uploading a file, you can use file1.postedfile. contenttype to read the mimie type of the file, which is obtained by the system by the extension name of the uploaded file.

4. Save the uploaded file:

1. The file can be saved through file1.postedfile. saveas (PATH) // path is the physical path on the server.

If (file1.postedfile. contentlength! = 0)

{

Stringbuilder mystr = new stringbuilder ();

Mystr. append ("file name:" + file1.postedfile. filename );

Mystr. append ("<br> ");

Mystr. append ("file type:" + file1.postedfile. contenttype );

Mystr. append ("<br> ");

Mystr. append ("file length:" + file1.postedfile. contentlength. tostring ());

Mystr. append ("<br> ");

String Path = server. mappath ("./"); // current path

String filename = file1.postedfile. filename. substring (file1.postedfile. filename. lastindexof ('//') + 1 );

Path + = filename;

If (file. exists (PATH) = true)

{

Label1.text = "the file you are uploading already exists on the server:" + filename;

Return;

}

File1.postedfile. saveas (PATH );

Mystr. append ("saved! ");

Mystr. append ("<br> ");

Label1.text = mystr. tostring ();

}

Else

{

Label1.text = "You have not selected the file to be uploaded or the length of the file to be uploaded is 0! ";

}

2. files can also be read in binary format and stored in binary fields of the database:
Byte [] filecont = new byte [file1.postedfile. contentlength];
File1.postedfile. inputstream. Read (filecont, 0, file1.postedfile. contentlength );
Then, the parameter that this byte array filecont assigns to the binary field of the database is written to the database.

File Download

1. The server outputs the corresponding HTTP Response Headers information through response and the data of the file to be downloaded to send the file to the client. The HTTP Response Headers is shown in the following form in the HTML file:
<Meta http-equiv = "Content-Type" content = "text/htm">
HTTP-equiv indicates the headers name, and content indicates the value of this headers.

2. First, the MIME type of the file to be output:
Page. response. addheader ("Content-Type", "MIME type ");

3. Second, output the Open Location and file name of the downloaded file:
Page. response. addheader ("content-disposition", "attachment; filename =" + filename );
Content-Disposition
The HTTP Response Header of allows you to specify the information in the document. Use this Header
You can specify to open the document separately (instead of in the browser), and display it according to user operations. If you want to save a document, you can also recommend a file name for this document. This suggestion
The name is displayed in the "file name" column of the Save As dialog box.
Open Location:
Attachment-the attachment is sent to the client, and the client opens the file separately.
Inline-indicates that the file will be opened in the browser.
File Name:
Filename-indicates the file name sent to the client.

4. file data to be sent to the client:

1. convert data from different types of sources into byte arrays, and then send the data to the client through the response. binarywrite method:

1.1. Read the file to obtain the byte array: String filename; // generate or retrieve the file name to be sent to the client

String filepath = server. mappath ("./") + filename; // assume that the file is in the current directory.

If (file. exists (filepath) = false)

{

// This file does not exist on the server

Return;

}

Filestream myfile = file. openread (filepath); // read the file into filestream

Byte [] filecont = new byte [myfile. Length];

Myfile. Read (filecont, 0, (INT) myfile. Length); // convert the content in the file stream to a byte array

1.2. Read in the binary field of the database: // obtain the image ID from the URL

String imageid = request. querystring ["IMG"];

// Construct a query statement

String sqltext = "select img_data, img_contenttype from image where img_pk =" + imageid;

Sqlconnection connection = new sqlconnection (configurationsettings. receivettings ["DSN"]. tostring ());

Sqlcommand command = new sqlcommand (sqltext, connection );

Connection. open ();

Sqldatareader DR = command. executereader ();

If (dr. Read ())

{

Byte [] filecont = (byte []) Dr ["img_data"];

}

Connection. Close ();

1.3. Reading files from the Internet: httpwebrequest mywebrequest = (httpwebrequest) webrequest. Create ("http://www.via.com/aa.xls

");

Httpwebresponse mywebresponse = (httpwebresponse) mywebrequest. getresponse ();

Stream readstream = mywebresponse. getresponsestream ();

Byte [] bytes = new byte [readstream. Length];

Bytes = readstream. Read (bytes, 0, readstream. Length );

The byte array of the file content obtained through the above three methods can be used to output:
Page. response. binarywrite (filecont );

Page. response. End ();

2. Directly read the file output: String filename; // generate or obtain the file name to be sent to the client

String filepath = server. mappath ("./") + filename; // assume that the file is in the current directory.

If (file. exists (filepath) = false)

{

// This file does not exist on the server

Return;

}

Page. response. Clear ();

Page. response. addheader ("Content-Type", "image/GIF"); // depending on the mime settings

Page. response. addheader ("content-disposition", "inline; filename =" + filepath );

Page. response. writefile (filepath );

Page. response. End ();

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.