C universal file upload class
- 2020-05-07 19:27:05
- OfStack
1, Upfile.aspx:
Upfile.aspx.cs
code
3, class file:
code
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Upfile.aspx.cs" Inherits="Inc_Upfile" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd";>
<html xmlns="http://www.w3.org/1999/xhtml"; >
<head runat="server">
<title> Upload a file </title>
<link href="../Manage/Style.Css" type="text/css" rel=Stylesheet />
</head>
<body>
<form id="form1" runat="server">
<div style="left: 0px; clip: rect(0px auto auto 0px); position: absolute; top: 0px">
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text=" Upload a file " CssClass="btn2" />
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label></div>
</form>
</body>
</html>
Upfile.aspx.cs
code
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class Inc_Upfile : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//Cut By Dream XiYuan.
}
protected void Button1_Click(object sender, EventArgs e)
{
AllSheng.upload UpFiles = new AllSheng.upload();
//HttpPostedFile File = FileUpload1.PostedFile;
// AllSheng.UploadObj.PhotoSave("/", FileUpload1);
HttpFileCollection files = HttpContext.Current.Request.Files;
UpFiles.Path = "../UpLoadfiles";
String ReStr= UpFiles.SaveAs(files).ToString();
Label1.Text = ReStr;
UpFiles = null;
}
}
3, class file:
code
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
/**//// <summary>
/// Cls_Upfile Summary of
/// </summary>
///
namespace AllSheng
{
public class upload
{
variable #region variable
System.Web.HttpPostedFile postedFile;
protected string localFileName;// The original name of the file ( With the extension )
protected string localFileExtension;// The original extension
protected long localFileLength;// Original file size
protected string localFilePath;// Original file path
protected string saveFileName;// Saved file name ( With the extension )
protected string saveFileExtension;// The saved extension
//protected long saveFileLength;// Saved file size
protected string saveFilePath;// Save the full path to the server side of the file
protected string saveFileFolderPath;// Save the folder path of the file on the server side
private string path = null;
private string fileType = null;
private int sizes = 0;
#endregion
upload(): Initialize variable #region upload(): Initialize variable
/**//// <summary>
/// Initialize variable
/// </summary>
public upload()
{
path = @"uploadimages"; // Upload path
fileType = "jpg|gif|bmp|jpeg|png|rar|doc";
sizes = 200; // Size of file passed , The default 200KB
}
#endregion
Sets the incoming value :Path/Sizes/FileType#region Sets the incoming value :Path/Sizes/FileType
/**//// <summary>
/// Set the upload path , Such as :uploadimages
/// </summary>
public string Path
{
set
{
path = @"" + value + @"";
}
}
/**//// <summary>
/// Set the upload file size , The unit is KB
/// </summary>
public int Sizes
{
set
{
sizes = value;
}
}
/**//// <summary>
/// Sets the type of file to upload , Such as :jpg|gif|bmp
/// </summary>
public string FileType
{
set
{
fileType = value;
}
}
#endregion
SaveAs() Upload a file #region SaveAs() Upload a file
public string SaveAs(System.Web.HttpFileCollection files)
{
string myReturn = "";
try
{
for (int iFile = 0; iFile < files.Count; iFile++)
{
postedFile = files[iFile];
// Get the upload path of the file
localFilePath = postedFile.FileName;
// Determines if the upload file path is empty
if (localFilePath == null || localFilePath == "")
{
//message(" You didn't upload the data, is there a mistake !");
//break;
continue;
}
else
{
Determining file size #region Determining file size
// Gets the size of the uploaded file
localFileLength = postedFile.ContentLength;
// Determine the upload file size
if (localFileLength >= sizes * 1024)
{
message(" The uploaded image cannot be larger than " + sizes + "KB");
break;
}
#endregion
folder #region folder
// Gets the save folder path
saveFileFolderPath = getSaveFileFolderPath(path);
#endregion
The file name #region The file name
// Get the original file name (with extension)
localFileName = System.IO.Path.GetFileName(postedFile.FileName);
saveFileName = DateTime.UtcNow.ToString("yyyy" + "MM" + "dd" + "HH" + "mm" + "ss" + "ffffff");//"yyyy"+"MM"+"dd"+"HH"+"mm"+"ss"+"ffffff"
#endregion
extension #region extension
// Gets the original file extension
localFileExtension = getFileExtension(localFileName);
// Upload is allowed if true , False is not allowed to upload
if (localFileExtension == "")
{
message(" At present, the format supported by this system is :" + fileType);
}
// Gets the extension to save the file , The extension can be changed as needed
saveFileExtension = localFileExtension;
#endregion
// Gets the full path to save the file
saveFilePath = saveFileFolderPath + saveFileName + saveFileExtension;
postedFile.SaveAs(saveFilePath);
myReturn = myReturn + ((myReturn == "" || myReturn == null) ? "" : "|") + path.TrimStart(new char[] { '' }) + saveFileName + saveFileExtension;
// The following is the content of the article 1 Some of the processing
System.Web.HttpContext.Current.Response.Write("<script>parent.Article_Content___Frame.FCK.EditorDocument.body.innerHTML+='<img src=" + saveFileName + saveFileExtension + " "+" border=0 />'</SCRIPT>");
}
}
}
catch
{
// abnormal
message(" Unknown error! ");
myReturn = null;
}
return myReturn;
}
#endregion
getSaveFileFolderPath( ): Gets the physical path to the saved folder #region getSaveFileFolderPath( ): Gets the physical path to the saved folder
/**//// <summary>
/// Gets the physical path to the saved folder
/// Returns the physical path to the saved folder , if null It's an error
/// </summary>
/// <param name="format"> The path to the saved folder or Format to create a folder to save the file, such as by date "yyyy"+"MM"+"dd":20060511</param>
/// <returns> The physical path to the saved folder , if null It's an error </returns>
private string getSaveFileFolderPath(string format)
{
string mySaveFolder = null;
try
{
string folderPath = null;
// Create a folder at the current time ,
//!!!!!!!!!!!! Replace the following validation statement with a regular expression !!!!!!!!!!!!!!!!!!!
if (format.IndexOf("yyyy") > -1 || format.IndexOf("MM") > -1 || format.IndexOf("dd") > -1 || format.IndexOf("hh") > -1 || format.IndexOf("mm") > -1 || format.IndexOf("ss") > -1 || format.IndexOf("ff") > -1)
{
// Create the name of the folder in common standard time
folderPath = DateTime.UtcNow.ToString(format);
mySaveFolder = System.Web.HttpContext.Current.Server.MapPath(".") + @"" + folderPath + @"";
}
else
{
mySaveFolder = System.Web.HttpContext.Current.Server.MapPath(".") + format;
}
System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(mySaveFolder);
// Determine whether the folder exists , Create if it does not exist
if (!dir.Exists)
{
dir.Create();
}
}
catch
{
message(" Error getting save path ");
}
return mySaveFolder;
}
#endregion
getFileExtension( ): Gets the extension of the original file #region getFileExtension( ): Gets the extension of the original file
/**//// <summary>
/// Gets the extension of the original file , Returns the extension of the original file (localFileExtension), This function USES external variables fileType, That is, the allowed file extension .
/// </summary>
/// <param name="myFileName"> The original name of the file </param>
/// <returns> The extension of the original file (localFileExtension); If return to null, Indicates that the file has no suffixed name ; If return to "", Indicates that the extension is illegal .</returns>
private string getFileExtension(string myFileName)
{
string myFileExtension = null;
// Gets the file extension
myFileExtension = System.IO.Path.GetExtension(myFileName);// if null, Indicates that the file has no suffixed name ;
// Break down the format of the file that is allowed to be uploaded
if (myFileExtension != "")
{myFileExtension = myFileExtension.ToLower();// Convert to lowercase
}
string[] temp = fileType.Split('|');
// Sets whether the uploaded file is in the allowed format
bool flag = false;
// Determines if the uploaded file is in the allowed format
foreach (string data in temp)
{
if (("." + data) == myFileExtension)
{
flag = true;
break;
}
}
if (!flag)
{
myFileExtension = "";// Can't be set to null, because null Indicates that the file has no suffixed name ;
}
return myFileExtension;
}
#endregion
message( ): Pop-up message box #region message( ): Pop-up message box
/**//// <summary>
/// Pop-up message box , According to the content (msg), Click on the " determine " Then the page jumps to the path (url)
/// </summary>
/// <param name="msg"> According to the content </param>
/// <param name="url"> Jump path </param>
private void message(string msg, string url)
{
System.Web.HttpContext.Current.Response.Write("<script language=javascript>alert('" + msg + "');window.location='" + url + "'</script>");
}
/**//// <summary>
/// Pop-up message box , According to the content (msg), There is no jump
/// </summary>
/// <param name="msg"> According to the content </param>
private void message(string msg)
{
System.Web.HttpContext.Current.Response.Write("<script language=javascript>alert('" + msg + "');</script>");
}
#endregion
}
}