Set of methods for uploading and downloading files in ASP. NET
Source: Internet
Author: User
File Upload/download is a technology that we often use in the actual project development process. Several common methods are provided here. The main content of this article includes:
1. How to Solve the file upload size limit
2. Save the file to the server
3. convert to a binary byte stream, save it to the database, and download it
4. Upload Internet Resources
Part 1:
First, let's talk about how to solve the file upload size limit in Asp.net. We know ASP by default.. Net file upload size is limited to 2 MB. In general, we can change the web. the config file defines the maximum file size as follows:
<Httpruntime executiontimeout = "300" maxrequestlength = "40960" usefullyqualifiedredirecturl = "false"/> in this way, the maximum value of the uploaded file is 4 MB, however, this does not allow us to infinitely expand the value of maxrequestlength, because ASP. net loads all files into the memory and then processes them. The solution is to use the implicit httpworkerrequest and its getpreloadedentitybody and readentitybody methods to read data from the pipe created by IIS for ASP. NET in blocks. The implementation method is as follows:
//
// Determine the file format based on the Type
//
Appconfig APP = new appconfig ();
String format = app. getpath ("fileupload/format ");
//
// Return if none of the formats are correct
//
If (format. indexof (fileextension) =-1)
{
Throw new applicationexception ("the format of uploaded data is invalid ");
}
//
// Generate a random file name based on the date and random number.
//
If (myfilename! = String. Empty)
{
Filename = myfilename;
}
If (israndom)
{
Random objrand = new random ();
System. datetime date = datetime. now;
// Generate random file names
Savename = date. year. tostring () + date. month. tostring () + date. day. tostring () + date. hour. tostring () + date. minute. tostring () + date. second. tostring () + convert. tostring (objrand. next (99) * 97 + 100 );
Filename = savename + fileextension;
}
// Return the information of the uploaded object
Return FP;
}
Then we can call this method when uploading files, and save the returned file information to the database. As for downloading, it is OK to open the path directly.
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.