Как проверить, все ли изображения полностью загружены в папку приложения MVC, а затем отправить эти изображения в текст сообщения?

Я загружаю несколько изображений в свою папку асинхронно, используя XMLHttpRequest. После того, как все изображения полностью загружены в папку, мне нужно отправить электронное письмо, которое содержит эти изображения в основной части письма, а также в приложении. У меня вопрос, как я могу проверить, все ли изображения полностью загружены в мою папку. Я пробовал следующее:

 $scope.UploadFile = function (inputFile) {
        var j = inputFile.length;
        var filenames = [];
        for (var i = 0; i < inputFile.length; i++) {
            $scope.UploadFileIndividual(inputFile[i].file,
                                        inputFile[i].file.name,
                                        inputFile[i].file.type,
                                        inputFile[i].file.size,
                                        i, inputFile.length);
            filenames[i] = inputFile[i].file.name;
            j--;
        }
        if (j == 0)
        {
            $http({
                method: 'POST',
                url: '/RFQ/SendEmail/',
                data: { RFQValues: $scope.RFQData, fileNames: filenames}
            }).success(function (response, status, headers, config) {
                if (response == true) {
                    window.location.href = '/CheckOut/ThankYou';
                }
            }).error(function (response, status, headers, config) {
                // alert('Your Selection Not Added to Cart');
            });
        }
    } ; 
    $scope.UploadFileIndividual = function (fileToUpload, name, type, size, index, fileArrayLength) {
        var reqObj = new XMLHttpRequest();
       
        //open the object and set method of call(get/post), url to call, isasynchronous(true/False)
        reqObj.open("POST", "/RFQ/UploadFiles", true);

        //set Content-Type at request header.For file upload it's value must be multipart/form-data
        reqObj.setRequestHeader("Content-Type", "multipart/form-data");

        //Set Other header like file name,size and type
        reqObj.setRequestHeader('X-File-Name', name);
        reqObj.setRequestHeader('X-File-Type', type);
        reqObj.setRequestHeader('X-File-Size', size);

        // send the file
        reqObj.send(fileToUpload);
    };
Это мой метод контроллера для загрузки изображений:

  public virtual string UploadFiles(object obj)
    {
        try
        {
            var length = Request.ContentLength;
            var bytes = new byte[length];
            Request.InputStream.Read(bytes, 0, length);

            var fileName = Request.Headers["X-File-Name"];
            var fileSize = Request.Headers["X-File-Size"];
            var fileType = Request.Headers["X-File-Type"];
            string path = @"~\images\Client Images";
            string subPath = System.Web.HttpContext.Current.Session["UserName"].ToString() + "_" + System.Web.HttpContext.Current.Session["UserId"].ToString();
            string finalPath = Server.MapPath(path + @"\" + subPath);
            if (!Directory.Exists(finalPath))
                Directory.CreateDirectory(finalPath);
            var saveToFileLoc = finalPath + @"\" + fileName;

            // save the file.
            var fileStream = new FileStream(saveToFileLoc, FileMode.Create, FileAccess.ReadWrite);
            fileStream.Write(bytes, 0, length);
            fileStream.Close();

            var usrid = Convert.ToInt32(System.Web.HttpContext.Current.Session["UserId"].ToString());
            using (DataContext _db = new DataContext())
            {
                int RFQId = _db.RFQDetailss.OrderByDescending(x => x.RFQId).Where(x => x.UserId == usrid && EntityFunctions.TruncateTime(x.RFQ_CreatedDate) == EntityFunctions.TruncateTime(DateTime.Now)).Select(y => y.RFQId).FirstOrDefault();

                RFQClientImage objClientImage = new RFQClientImage();
                objClientImage.RFQId = RFQId;
                objClientImage.ImagePath = @"images\Client Images\" + subPath + @"\" + fileName;
                _db.RFQClientImages.Add(objClientImage);
                _db.SaveChanges();
            }
            return string.Format("{0} bytes uploaded", bytes.Length);
        }
        catch
        {
            return "";
        } 
    }

Затем я проверил на стороне js, отправляются ли все файлы для загрузки, а затем в контроллере, а также проверяю, существуют ли загруженные в данный момент файлы в папке, с помощью следующего кода:

public JsonResult SendEmail(RFQFormInfo RFQValues, string[] fileNames)
    {
        bool IsMailSent = false;
        try
        {
            string directoryPath = @"~\images\Client Images\";
            string subDirectoryPath = System.Web.HttpContext.Current.Session["UserName"].ToString() + "_" + System.Web.HttpContext.Current.Session["UserId"].ToString() + @"\";
            //string[] fileEntries = Directory.GetFiles(Server.MapPath(directoryPath + subDirectoryPath));
            string targetPath = Server.MapPath(directoryPath + subDirectoryPath);
            IsMailSent = checkifImageUploaded(RFQValues, getFilesList(targetPath), fileNames);
            return Json(IsMailSent, JsonRequestBehavior.AllowGet);
        }
        catch
        {
            return Json(IsMailSent, JsonRequestBehavior.AllowGet);
        }
    }

    public bool checkifImageUploaded(RFQFormInfo RFQValues, IEnumerable<string> fileEntries, string[] fileNames)
    {
        bool IsMailSent = false;
        try
        {
            int counter = 0;
            string directoryPath = @"~\images\Client Images\";
            string subDirectoryPath = System.Web.HttpContext.Current.Session["UserName"].ToString() + "_" + System.Web.HttpContext.Current.Session["UserId"].ToString() + @"\";
            string targetPath = Server.MapPath(directoryPath + subDirectoryPath);
            foreach (string filename in fileNames)
            {
                var currentFile = Server.MapPath(directoryPath + subDirectoryPath + filename);
                 foreach(var file in fileEntries)
                 {
                     if (file.Equals(currentFile))
                     {
                         counter++;
                         break;
                     }
                 }
                 if (counter == fileNames.Length)
                     break;
            }
            if (counter == fileNames.Length)
            {
                IsMailSent = SendRFQMail(RFQValues, fileNames);
                return IsMailSent;
            }
            else
                checkifImageUploaded(RFQValues, getFilesList(targetPath), fileNames);

            return IsMailSent;
        }
        catch
        {
            return IsMailSent;
        }
    }

    public IEnumerable<string> getFilesList(string targetDirectory)
    {
        var fileEntries = Directory.EnumerateFiles(targetDirectory);
        return fileEntries;
    }

но моя функция checkIfImageUploaded() выдает исключение переполнения стека. Я понимаю, что это потому, что мой код заканчивается бесконечным циклом или рекурсией, но я не понимаю, в какой момент мой код заканчивается бесконечной рекурсией и как ее решить.

Пожалуйста, помогите мне. Заранее спасибо.

0 ответов

Другие вопросы по тегам