1. The files uploaded to the server cannot have the same name. Use the original name of the guid_ file to save to avoid duplicate names.
2. Solve the problem that a large number of files are stored in the same directory, and use the directory separation algorithm to ensure that different pictures are stored in different directories.
The full code is as follows:
// Calculate a new file name by guid + old file name string new_fileName = Guid.NewGuid().ToString() + "_" + Path.GetFileName(fileData.FileName);
2. Solve the problem that a large number of files are stored in the same directory, and use the directory separation algorithm to ensure that different pictures are stored in different directories.
//Get the hash code of the current new_fileName, which is an integer. int hash_code = new_fileName.GetHashCode(); //2. Use the integer and the binary value "1111" (that is, the hexadecimal value: 0xf) and get the last 4 of the current integer as the value. int dir1 = hash_code & 0xf;//The first level directory //Any class inherits from the object class. There is a method GetHashCode() in the object class to get the hash code of the current object. // Shift the original hash_code value 4 bits to the right. , hash_code = hash_code >> 4; int dir2 = hash_code & 0xf;//Get the second level directory //A total of eight layers, it is recommended to encapsulate it as a method, and only write to the second layer here //path stitching string targetFilePath = Path.Combine(context.Request.MapPath("upload/"), dir1.ToString(), dir2.ToString()); / / Determine whether the current folder exists, if not, create a folder if (!Directory.Exists(targetFilePath)) { Directory.CreateDirectory(targetFilePath); } //2. Save the file uploaded by the user as a directory on the server. // Concatenate the file name with the directory. targetFilePath = Path.Combine(targetFilePath, new_fileName);
3. Determine whether the upload by the user is a picture, and only allow pictures to be uploaded.
if ((ext == ".jpg" || ext == ".jpeg" || ext == ".png" || ext == ".gif" || ext == ".bmp") && fileData.ContentType.ToLower().StartsWith("image")) {}
The full code is as follows:
public class ProcessUpload : IHttpHandler { public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/plain"; //1. Get the file uploaded by the user if (context.Request.Files.Count > 0) { //Get the uploaded file in the first file field HttpPostedFile fileData = context.Request.Files[0]; / / Determine whether the number of bytes of the uploaded file is greater than 0 if (fileData.ContentLength > 0) { string ext = Path.GetExtension(fileData.FileName); if ((ext == ".jpg" || ext == ".jpeg" || ext == ".png" || ext == ".gif" || ext == ".bmp") && fileData.ContentType.ToLower().StartsWith("image")) { #region Calculate the file name and directory, save the file // Calculate a new file name by guid + old file name string new_fileName = Guid.NewGuid().ToString() + "_" + Path.GetFileName(fileData.FileName); //Get the hash code of the current new_fileName, which is an integer. int hash_code = new_fileName.GetHashCode(); //2. Use the integer and the binary value "1111" (that is, the hexadecimal value: 0xf) and get the last 4 of the current integer as the value. int dir1 = hash_code & 0xf;//The first level directory //Any class inherits from the object class. There is a method GetHashCode() in the object class to get the hash code of the current object. // Shift the original hash_code value 4 bits to the right. , hash_code = hash_code >> 4; int dir2 = hash_code & 0xf;//Get the second level directory //A total of eight layers, it is recommended to encapsulate it as a method, and only write to the second layer here //path stitching string targetFilePath = Path.Combine(context.Request.MapPath("upload/"), dir1.ToString(), dir2.ToString()); / / Determine whether the current folder exists, if not, create a folder if (!Directory.Exists(targetFilePath)) { Directory.CreateDirectory(targetFilePath); } //2. Save the file uploaded by the user as a directory on the server. // Concatenate the file name with the directory. targetFilePath = Path.Combine(targetFilePath, new_fileName); fileData.SaveAs(targetFilePath); #endregion context.Response.Write("The file was uploaded successfully!"); } else { context.Response.Write("Illegal file!"); } } } } public bool IsReusable { get { return false; } } }
front-end code
<!------- upload file-------------> <!-- 1. Notes for uploading client forms: 1> The form submission method must be post. method="post" 2> The data organization method when submitting data in the table must be modified, set enctype, enctype="multipart/form-data" By default, the enctype of the form is set as follows: enctype="application/x-www-form-urlencoded". After setting this item, it is actually set to the Content-Type of the request header. With this setting, the final data in the form is organized in a way similar to the following: txtName=%E9%9A%9C %E7%A2%8D%E6%98%AF%E5%93%AA%E4%B8%AA&txtPhone=13888888888&[email protected]&selGroups=3 //When setting enctype="multipart/form-data", the data submission method is organized by dividing lines. 3> There needs to be a file field in the form. --> <form action="ProcessUpload.ashx" method="post" enctype="multipart/form-data"> <p> Please select a file to upload: <input id="fileData" type="file" name="fileData" value="" /> </p> <input id="btnSubmit" type="submit" value="提交" /> </form>
document dowload
Just set the Content-Disposition value of the response to let the browser know that this is a download.
string encodeFileName = HttpUtility.UrlEncode("aa.txt");//International use to prevent garbled characters. generate ASCII
context.Response.AddHeader("Content-Disposition", string.Format("attachment;filename=\"{0}\"", encodeFileName));//Add Content-Disposition to the response header, attachment means attachment form download.
context.Response.WriteFile("aa.txt");//Output file content, file path