Uploading and downloading files is a technology we often need to use in the actual project development process. Here are several common methods. The main contents of this article include:
1. How to solve the file upload size limit
2. Save to server as file
3. Convert to binary byte stream and save to database and download method
4. Upload resources on the Internet
Part 1:
First, let’s talk about how to solve the problem of file upload size limit in ASP.NET. We know that by default, the file upload size limit of ASP.NET is 2M. In general, we can customize it by changing the WEB.Config file. The maximum file size is as follows:
<httpRuntime executionTimeout="300" maxRequestLength="40960" useFullyQualifiedRedirectUrl="false"/>In this way, the maximum value of the uploaded file becomes 4M, but this does not allow us to infinitely expand the value of MaxRequestLength, because ASP.NET will After all files are loaded into memory, they are processed. The solution is to use the implicit HttpWorkerRequest and use its GetPreloadedEntityBody and ReadEntityBody methods to read data in chunks from the pipe created by IIS for ASP.NET. The implementation method is as follows:
IServiceProviderprovider=(IServiceProvider)HttpContext.Current;
HttpWorkerRequestwr=(HttpWorkerRequest)provider.GetService(typeof(HttpWorkerRequest));
byte[]bs=wr.GetPreloadedEntityBody();
.
if(!wr.IsEntireEntityBodyIsPreloaded())
{
intn=1024;
byte[]bs2=newbyte[n];
while(wr.ReadEntityBody(bs2,n)>0)
{
..
}
}This will solve the problem of uploading large files.
Part 2:
Next we will introduce how to upload a file from the client to the server in the form of a file and return some basic information about the uploaded file. First, we define a class to store the information about the uploaded file (required when returning).
public class FileUpLoad
{
public FileUpLoad()
{
}
/**//// <summary>
/// Upload file name
/// </summary>
public string FileName
{
get
{
return fileName;
}
set
{
fileName = value;
}
}
private string fileName;
/**//// <summary>
/// Upload file path
/// </summary>
public string FilePath
{
get
{
return filepath;
}
set
{
filepath = value;
}
}
private string filepath;
/**//// <summary>
/// File extension
/// </summary>
public string FileExtension
{
get
{
return fileExtension;
}
set
{
fileExtension = value;
}
}
private string fileExtension;
}
In addition, we can also limit the format of uploaded files in the configuration file (App.Config):
<?xml version="1.0" encoding="gb2312" ?>
<Application>
<FileUpLoad>
<Format>.jpg|.gif|.png|.bmp</Format>
</FileUpLoad>
</Application>
In this way we can start writing our method of uploading files, as follows:
public FileUpLoad UpLoadFile(HtmlInputFile InputFile,string filePath,string myfileName,bool isRandom)
{
FileUpLoad fp = new FileUpLoad();
string fileName,fileExtension;
string saveName;
//
//Create upload object
//
HttpPostedFile postedFile = InputFile.PostedFile;
fileName = System.IO.Path.GetFileName(postedFile.FileName);
fileExtension = System.IO.Path.GetExtension(fileName);
//
//Determine file format based on type
//
AppConfig app = new AppConfig();
string format = app.GetPath("FileUpLoad/Format");
//
//If the format does not match, return
//
if(format.IndexOf(fileExtension)==-1)
{
throw new ApplicationException("The uploaded data format is illegal");
}
//
//Generate a random file name based on date and random number
//
if(myfileName != string.Empty)
{
fileName = myfileName;
}
if(isRandom)
{
Random objRand = new Random();
System.DateTime date = DateTime.Now;
//Generate random file name
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;
}
string phyPath = HttpContext.Current.Request.MapPath(filePath);
//Determine whether the path exists, if not, create the path
DirectoryInfo upDir = new DirectoryInfo(phyPath);
if(!upDir.Exists)
{
upDir.Create();
}
//
//save file
//
try
{
postedFile.SaveAs(phyPath + fileName);
fp.FilePath = filePath + fileName;
fp.FileExtension = fileExtension;
fp.FileName = fileName;
}
catch
{
throw new ApplicationException("Upload failed!");
}
//Return the information of the uploaded file
return fp;
}
Then we can call this method when uploading files, and save the returned file information to the database. As for downloading, just open the path directly and it will be OK.
Part Three:
Here we mainly talk about how to upload and download files in binary form. First, let’s talk about uploading. The method is as follows:
public byte[] UpLoadFile(HtmlInputFile f_IFile)
{
//Get access to the uploaded file specified by the client
HttpPostedFile upFile=f_IFile.PostedFile;
//Get the length of the uploaded file
int upFileLength=upFile.ContentLength;
//Get the client MIME type of the uploaded file
string contentType = upFile.ContentType;
byte[] FileArray=new Byte[upFileLength];
Stream fileStream=upFile.InputStream;
fileStream.Read(FileArray,0,upFileLength);
}This method returns the binary byte stream of the uploaded file, so that we can save it to the database. Let’s talk about this form of downloading. You may think that downloading in this way is to create a new aspx page, then take out the binary byte stream in its Page_Load() event, and then read it out. In fact, this This method is not advisable. In actual application, there may be an error that cannot open a certain site. I generally use the following method:
First, add: to Web.config:
<add verb="*" path="openfile.aspx" type="RuixinOA.Web.BaseClass.OpenFile, RuixinOA.Web"/>
This means that when I open the page openfile.aspx, the system will automatically execute the methods in the RuixinOA.Web.BaseClass.OpenFile class. The specific implementation is as follows:
using System;
using System.Data;
using System.Web;
using System.IO;
using Ruixin.WorkFlowDB;
usingRXSuite.Base;
usingRXSuite.Component;
using RuixinOA.BusinessFacade;
namespace RuixinOA.Web.BaseClass
{
/**//// <summary>
/// Summary description of NetUFile.
/// </summary>
public class OpenFile : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
//Get the file information to be downloaded from the database
RuixinOA.BusinessFacade.RX_OA_FileManager os = new RX_OA_FileManager();
EntityData data = os.GetFileDetail(id);
if(data != null && data.Tables["RX_OA_File"].Rows.Count > 0)
{
DataRow dr = (DataRow)data.Tables["RX_OA_File"].Rows[0];
context.Response.Buffer = true;
context.Response.Clear();
context.Response.ContentType = dr["CContentType"].ToString();
context.Response.AddHeader("Content-Disposition","attachment;filename=" + HttpUtility.UrlEncode(dr["CTitle"].ToString()));
context.Response.BinaryWrite((Byte[])dr["CContent"]);
context.Response.Flush();
context.Response.End();
}
}
public bool IsReusable
{
get { return true;}
}
}
}
After executing the above method, the system will prompt the user to choose to open directly or download. That’s it for this part.
Part 4:
This part mainly talks about how to upload a resource on the Internet to the server. We have a previous article that details how to use it, so I won’t say more here.
Please refer to: Convert dynamic pages into binary byte streams
Part 5: Summary
Today I briefly introduce several methods of file upload and download, which are often used in actual project development. There may be imperfections. I hope everyone can exchange their experience in project development. Please correct me if I write poorly, thank you!
Email:[email protected]