Пример #1
0
        public async Task <ActionResult <LoadReport> > UploadFilesAsync()
        {
            // hardcoded max lenght for file and path in windows because not easy to retrieve this limit from .net
            //const int maxPathLenght = 255;
            const int maxFileNameLenght = 45;

            _dictFile = new LoadReport();
            try
            {
                // Create upload folder if not there is
                var result = Directory.CreateDirectory(_uploadFolder);
            }
            catch (Exception ex)
            {
                _logger.LogError("Exception trying to create upload folder: " + ex.Message);
            }
            if (Request.HasFormContentType)
            {
                var form = Request.Form;
                if (form.Files != null && form.Files.Count > 0)
                {
                    foreach (var formFile in form.Files)
                    {
                        // Filter for extension
                        // upload only extension allowed
                        if (Path.GetExtension(formFile.FileName).ToLower() == _fileExtensionAllowedToUpload)
                        {
                            var uniquefilename = UniqueFilename.GenerateUniqueFilename(formFile);
                            //var savePath = _uploadFolder + "\\" + uniquefilename;
                            var currentPathLenght = _uploadFolder.Length + uniquefilename.Length;
                            // check if savepath have lenght greater than max allowed
                            if (currentPathLenght > maxFileNameLenght) // truncate exceeding part of path + filename to stay into maxFileNameLenght limit
                            {
                                uniquefilename = TruncateFilename.Truncate(uniquefilename, Math.Abs(maxFileNameLenght));
                            }
                            var savePath = _uploadFolder + "\\" + uniquefilename;
                            _dictFile.DictionaryOfFiles.Add(formFile.FileName, uniquefilename);


                            using (var fileStream = new FileStream(savePath, FileMode.Create))
                            {
                                formFile.CopyTo(fileStream);
                            }
                        }
                        else
                        {
                            _logger.LogInformation("Uploading for files with extension dont allowed, is skipped!");
                            //return BadRequest("Il file non è un file di Esxcel valido ! ");
                        }
                    }
                }
            }
            await CaricaSmarriti();

            return(Ok(_dictFile));
        }