asp.net file upload operation

Source: Internet
Author: User
Tags format file size file system file upload html form split tostring valid
Asp.net| Upload

Uploading a file in an ASP is a hassle, and needs to be supported by components like the old farmer. Things have become much simpler in asp.net.
Examples of uploading pictures below.
Declare the use of namespaces first. Using System.IO;
Drag an input (File) control into the design page and run it as a server control. The ID is myfile, then drag into a button and add the following code to the button's Click Time:

protected void Submit_click (object sender, EventArgs e)
{
string phname = This.txtName.Text;
string phtype = This.ddlType.SelectedValue;

if (this.myFile.PostedFile!= null)
{
string photoName1 = MyFile.PostedFile.FileName; Get the initial file name
int i = Photoname1.lastindexof ("."); Gets the last "." in the filename. The index
String newext = Photoname1.substring (i); Get file name extension
if (Newext!= ". gif" && newext!= ". jpg" &&newext!= ". jpeg" && newext!= ". bmp" && Newext!= ". png")
{
Response.Write ("Incorrect file format!");
Response.End ();
}
DateTime now = DateTime.Now; Get system time
String photoName2 = now.Millisecond.ToString () + "_" + myFile.PostedFile.ContentLength.ToString () + Newext; Rename file again, time millisecond part + file size + extension
MyFile.PostedFile.SaveAs (Server.MapPath ("photos" + photoName2)); Saves the file to the path, using Server.MapPath () to take the absolute directory of the current file. In asp.net "\" must be replaced with ""
}
}

The HtmlInputFile object corresponds to an HTML file INPUT element. You can access it by using the name specified by the id attribute. It has the following characteristics:
* PostedFile: Upload the contents of the file.
* Accept: A comma-delimited list of MIME types that specifies the types of files that may be committed.
* MaxLength: The longest file name length (including the path) to be submitted.
* Size: User input/Select the text box width of the uploaded file.
The following are the methods and features of HTML input control:
* FileName: A fully qualified file name on the user's computer. It also contains the local path to the uploaded file.
* ContentLength: Size of the uploaded file (bytes).
* ContentType: The MIME content type of the uploaded file.
* InputStream: Returns a Stream object that points to the uploaded file, allowing you to read the contents of the file.
* SaveAs: Easy to save the content of uploaded files.

================== related articles ===================


Uploading files to the server using ASP.net


File upload technology is a very practical technology, has a very wide range of applications, In ASP.net's own previous version of the ASP to implement this function, you must use Third-party components or the development of their own components, now, the implementation of the asp.net is much simpler, we do not need to use any components to achieve the upload function.
To facilitate the explanation, we can upload the file into two types: Single file upload and multiple file upload.

Single File Upload
Let's first introduce a single file upload method, single file upload is relatively simple,
Here is the complete code to implement a single file upload:

<%@ Import namespace= "System"%>
<%@ Import namespace= "System.Web.HttpPostedFile"%>
<%@ Import namespace= "System.Web.UI.HtmlControls.HtmlInputFile"%>
<script language= "VB" runat= "Server" >
Sub UpLoad (Src as Object, E as EventArgs)
If Uploadfile.postedfile.contentlength=0 Then
showuploadfile.innertext= "Upload failed or file does not exist!" "
Else
' Get filename
Dim Temp () as String=split (UploadFile.PostedFile.FileName, "\")
Dim FileName As String=temp (temp.length-1)
' Save file
UploadFile.PostedFile.SaveAs (Server.MapPath (".") & "\files\" & FileName)
' Show upload results
Showuploadfile.innerhtml= "File Upload success!" <br> upload filename: "& filename
End If
End Sub
</script>
<body>
<form runat= "Server" enctype= "Multipart/form-data" >
<input type= "File" id= "UploadFile" runat= "Server" size= "M" ><br>
<asp:button runat= "Server" text= "Upload Now"/>
</form>
<span id= "Showuploadfile" runat= "Server" ></span>
</body>

Save the above code as an. aspx file, and then create a new directory in the directory where the file is located. Files, run, feel the effect, and then continue to read the following
Uploading files using ASP.net requires two classes of the. NET Framework: Httppostedfile and HtmlInputFile, where the namespaces are System.Web.HttpPostedFile and System.Web.UI.HtmlControls.HtmlInputFile, so we're going to import these two namespaces at the beginning of the file,
The PostedFile represents the file uploaded to the server, which contains several commonly used properties:
ContentLength: File size;
FileName: Upload the file details of the path and filename;
ContentType: File type for uploading files.
Character Split function split is used to get the filename, because the postedfile.filename gets the detailed path and filename.

Multiple file uploads
The so-called multi-file upload is to upload multiple files at the same time, this is the same as a single file upload is the same, the difference is that multiple files upload all files as a collection of files uploaded to the server, we need to be the collection of this file into a single file, The rest of the processing is the same as a single file upload.
First you need to know how many files to upload at the same time, and then you put the following Htmlinput controls between the form:
<input type= "File" runat= "server" size= "M" >
Note: Here the Htmlinput control control is not required to set the ID
How do I get a file out of a collection of files uploaded to the server? Look at the following code:

Dim i As Integer
For I=0 to Request.files.count-1
' Use Request.Files () to get uploaded files one by one
Dim myFile As Httppostedfile=request.files (i)
' Here the myfile is equivalent to the example in the PostedFile, you can use Myfile.filename to get the file name, etc
' The processing code here is the same as a single file upload.
Next

Now you have mastered the ASP.net file upload technology, as long as flexible application, beautify upload interface, make good asp.net upload program is not difficult.

=========================================

Apply asp.net upload files to a Web server

Many websites collect data through web pages, such as user feedback and blog posts. It's nice to be able to collect text. However, we often need to collect more robust factors. For example, many recruiting websites collect resumes submitted by job seekers in Word files. Standard HTML supports file upload, but if you apply asp.net upload, you can also get some additional functionality.

Input label

The standard HTML input tag supports file type attributes so that files can be uploaded to the network server. The following is the format of this label:

<input type= "File" name= "FileUpload"/>

Place the input label in an HTML form element. The code in List a shows the file upload control used in the ASP.net page.

Applying the upload tag to the ASP.net page also has two other properties: ID and runat. The ID property accesses the element by program, and the Runat property indicates the location of the processing element. The Runat property is set by the server, so it is handled by a network server. In addition, HTML contains the other elements that align the page items, and a button that submits the form.

The file Upload element provides the user with two options for uploading files: Enter the file path in the input text box, or select the Browse button to select from the local file system. Once the user has specified the file and then selects the Submit button, the network server takes over. (You need to use code to process the requested and uploaded files.) )

Upload with asp.net

There are several ways to upload files using asp.net, so let's take a look at a few situations. The most basic way is to apply the upload input control characteristics and methods. The following are the methods and features of HTML input control:

* FileName: A fully qualified file name on the user's computer. It also contains the local path to the uploaded file.
* ContentLength: Size of the uploaded file (bytes).
* ContentType: The MIME content type of the uploaded file.
* InputStream: Returns a Stream object that points to the uploaded file, allowing you to read the contents of the file.
* SaveAs: Easy to save the content of uploaded files.
The C # language instance in List B expands the first code sample to process the uploaded file. (the corresponding vb.net instance is in List C.) This page returns to process the upload file. ContentLength property to avoid uploading empty files. FileName Saves the file locally using the string method that extracts the file name from the file's local path. The SaveAs method saves the file in the network server folder. The btnsubmit button triggers the upload file process with its ASP.net OnServerClick event that points to the form method.

Its code applies htmlinputfile and Httppostedfile classes. The full path of these classes (and their collections) is:

* System.Web.UI.HtmlControls.HtmlInputFile
* System.Web.HttpPostedFile

Creates a Htmlputfile object when entering a file element (in our case, fileupload). The Httppostedfile object is created when the file is submitted to the server by the form (with the HtmlInputFile object). The Httppostedfile object is valid only in the postback event of the page.

The HtmlInputFile object corresponds to an HTML file INPUT element. You can access it by using the name specified by the id attribute. It has the following characteristics:

* PostedFile: Upload the contents of the file.
* Accept: A comma-delimited list of MIME types that specifies the types of files that may be committed.
* MaxLength: The longest file name length (including the path) to be submitted.
* Size: User input/Select the text box width of the uploaded file.

After you select a file, you can save the file in code. The HtmlInputFile PostedFile property controls whether the file is valid. The instance code works fine when the page on which the file is submitted is the same page as the page that handles the upload, but this is not always the case. Let's take a look at how to process file uploads on different pages!
Process uploads on different pages

In a recent project, I applied a flash based interface to collect user feedback and upload files. The Flash object is contained in an HTML file, while the upload process and content are located in another ASP.net page. The. NET framework makes this process easier.

The ASP.net request object contains everything that is submitted by the user. The files feature of the request class makes it easy to access the file uploaded by the user. The files attribute returns an instance of the Httpfilecollection class, which is a collection of Httppostedfile objects (that is, files submitted by the user). These two classes can easily handle the imported files. The C # instance in List D illustrates this process. (list e contains the corresponding vb.net instance.) )

This code restores the uploaded file set through the Httpfilecollection object, processes each upload file with a For loop, httppostedfile the object, and invokes the SaveAs method for each object, saving it on the network server.

Network pages can invoke the script through the behavior properties of the form. It should point to the ASP.net page. The HTML code in list F is a sample.

Safety

You should create a folder on the Web server and save the file in the directory specified by the code. In addition, you have to limit the type of upload file, for example, you want to block malicious code, large video, and the server caused trouble content.

You can use the MIME type of the file to restrict the file type that the user uploads. The HTML standard contains an INPUT element's behavior attribute that you can use to restrict the content of the upload by including a legitimate MIME type. See List G.

Not all network users support attributes, and the use of code solutions is more reliable. The code in List H modifies the first instance to accept only the word text. If the content type of the uploaded file is the MIME type of Microsoft Word, only the file is saved.

Accept All Files

Since the uploading of input elements, accepting file uploads is a standard network practice, which has not changed much. However, ASP. NET simplifies the process of submitting files. by asp.net pages, or standard HTML forms, you can easily handle the submission process and limit what users are uploading.



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.