Upload
Boolean fileOk = false;
Specify the file path, pic is a folder under the project; ~ indicates the folder where the current page is located
Httppostedfile postedFile = Request. Files[0];
string filename = DateTime.Now.ToString ("Yyyymmddhhmmss");
String FilePath = "/upload/pic/" + DateTime.Now.ToString ("yyyyMMdd") + "/";
String path = HttpContext.Current.Server.MapPath (FilePath);//Physical file path
File Upload Control If the file is already included
String ffname = String. Empty;
if (Postedfile.contentlength > 0)
{
Get the suffix of the file
String fileextension = path.getextension (postedfile.filename). ToLower ();
FileExtension = fileextension.substring (1);
Allow suffix of file
string[] allowedextensions = configurationmanager.appsettings["Uploadpic"]. Split (', ');
See if the included file is a suffix of the allowed file
for (int i = 0; i < allowedextensions.length; i++)
{
if (fileextension = = Allowedextensions[i])
{
FileOk = true;
Break
}
}
if (fileOk = = False)
{
msg= "{\" msg\ ": \" Picture is not properly formatted! \ ", \" Success\ ": false}";
return null;
}
Else
{
Try
{
File exists under the specified directory of the server
if (! Directory.Exists (PATH))
Directory.CreateDirectory (path);
Ffname = filename + path.getextension (postedfile.filename);
Postedfile.saveas (path + ffname);
return FilePath + ffname;
}
Catch
{
msg= "{\" msg\ ": \" Picture upload failed! \ ", \" Success\ ": false}";
return null;
}
}
}
return null;
Download
protected void Page_Load (object sender, EventArgs e)
{
String url = request.querystring["url"]; File relative path from reception
if (file.exists (HttpContext.Current.Server.MapPath (URL)))//Get an absolute path based on a relative path and then determine if the file exists
{
FileInfo DownloadFile = new FileInfo (HttpContext.Current.Server.MapPath (URL)); Get a file object based on an absolute path
HttpContext.Current.Response.Clear ();
HttpContext.Current.Response.ClearHeaders ();
HttpContext.Current.Response.Buffer = false;
HttpContext.Current.Response.ContentType = "Application/octet-stream";
HttpContext.Current.Response.AppendHeader ("Content-disposition", "attachment;filename=" + httputility.urlencode ( Downloadfile.name));
HttpContext.Current.Response.AppendHeader ("Content-length", DownloadFile.Length.ToString ());
HttpContext.Current.Response.WriteFile (Downloadfile.fullname);
HttpContext.Current.Response.Flush ();
HttpContext.Current.Response.End ();
}
}
How to upload and download files for ASP.