Thứ Tư, 8 tháng 7, 2020

asp:FileUpload upload file lên server C# asp webform

HTML:
<div class="upload">
            <asp:FileUpload ID="FileUploadControl" runat="server" />
            <asp:Button runat="server" ID="UploadButton" Text="Upload" OnClick="UploadButton_Click"  />
            <br />
            <br />
            <asp:Label runat="server" ID="StatusLabel" Text="Upload status: " />
        </div>

Code Behind:
protected void UploadButton_Click(object sender, EventArgs e)
        {
            if (FileUploadControl.HasFile)
            {
                try
                {
                    List<string> acceptContentType = new List<string> { "image/jpg", "image/png", "image/jpeg" };
                    string fileUploadContentType = FileUploadControl.PostedFile.ContentType;

                    bool isImage = acceptContentType.Contains(fileUploadContentType);

                    if (isImage)
                    {
                        if (FileUploadControl.PostedFile.ContentLength < 102400)
                        {
                            string uploadFolder = Server.MapPath("~/Upload/");

                            string uploadFileName = Path.GetFileName(FileUploadControl.FileName);

                            SaveAs(uploadFolder, uploadFileName, FileUploadControl);

                            StatusLabel.Text = "Upload status: File uploaded!";
                        }
                        else
                            StatusLabel.Text = "Upload status: The file has to be less than 100 kb!";
                    }
                    else
                        StatusLabel.Text = "Upload status: Only JPG/PNG/JPEG files are accepted!";
                }
                catch (Exception ex)
                {
                    StatusLabel.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
                }
            }
        }

        /// <summary>
        /// Lưu file và thêm hậu tố (i) nếu trùng tên
        /// </summary>
        /// <param name="uploadFolder">Ex: Server.MapPath("~/Upload/");</param>
        /// <param name="uploadFileName">Ex: filename.png</param>
        /// <param name="fileUploadControl">asp:FileUpload control ID</param>
        protected void SaveAs(string uploadFolder, string uploadFileName, FileUpload fileUploadControl)
        {
            //string uploadFolder = Server.MapPath("~/Upload/");
            //string uploadFileName = Path.GetFileName(FileUploadControl.FileName);

            string uploadBaseFileName = Path.GetFileNameWithoutExtension(uploadFileName);
            string uploadBaseFileExtension = Path.GetExtension(uploadFileName);

            string uploadFilePath = uploadFolder + uploadFileName;

            if (File.Exists(uploadFilePath))
            {
                DirectoryInfo d = new DirectoryInfo(uploadFolder);
                FileInfo[] Files = d.GetFiles();
                string itemFileName = "";
                string itemBaseFileName = "";
                string itemBaseFileExtension = "";
                string itemBaseFileNameCompare = "";
                int count = 0;
                List<int> lstNumberId = new List<int>();

                foreach (FileInfo itemFile in Files)
                {
                    itemFileName = itemFile.Name;
                    itemBaseFileName = Path.GetFileNameWithoutExtension(itemFileName);
                    itemBaseFileExtension = Path.GetExtension(itemFileName);

                    //regex
                    Regex reg = new Regex(@"\((\d+)(?!.*\d)\).*$"); // (1).png

                    Match result = reg.Match(itemFile.Name);
                    string rs = result.ToString();
                 
                    if (rs != "")
                        itemBaseFileNameCompare = itemFileName.Replace(rs, "");
                    else
                        itemBaseFileNameCompare = itemBaseFileName;
                    //

                    if ((itemBaseFileNameCompare == uploadBaseFileName || itemFileName == uploadFileName) && itemBaseFileExtension == uploadBaseFileExtension)
                    {
                        string trim = itemFileName.Replace(uploadFileName, ""); // (1).png
                        Regex regLastNumber = new Regex(@"(\d+)(?!.*\d)"); // 1 in (1).png
                        Match resultLastNumber = regLastNumber.Match(trim);
                        string rsLastNumber = resultLastNumber.ToString();
                        if (rsLastNumber != "")
                            lstNumberId.Add(Convert.ToInt32(rsLastNumber));

                        count++;
                    }
                }

                // nếu (i) đã có thì tăng count lên max + 1
                if (lstNumberId.Contains(count))
                {
                    count = lstNumberId.Max() + 1;
                }
                //new filePath
                uploadFilePath = String.Format("{0}{1}({2}){3}", uploadFolder, uploadBaseFileName, count, uploadBaseFileExtension);
            }

            fileUploadControl.SaveAs(uploadFilePath);
        }

Không có nhận xét nào:

Đăng nhận xét