Пример #1
0
 public ActionResult <ConvertResponse> Convert(Stream stream, string fileName)
 {
     try
     {
         string fileExtension = Path.GetExtension(fileName).Trim('.');
         if (stream.Length == 0)
         {
             throw new Exception("Поток не может быть пуст");
         }
         if (CheckFileExtension.GetFileExtension(fileExtension) == FileExtension.Extensions.Unknown)
         {
             throw new Exception("Неподдерживаемый тип файла");
         }
         if (CheckFileExtension.GetFileExtension(fileExtension) == FileExtension.Extensions.Pdf)
         {
             throw new Exception("Выберите другой файл, конвертация pdf в pdf не нужна");
         }
         _logger.LogDebug($"Start convert");
         ConvertResponse     responseConvert = new ConvertResponse();
         byte[]              result          = _fileInfoPdf.Convert(stream, fileName);
         ConvertFileResponse convertResult   = new ConvertFileResponse {
             Name = fileName, Pdf = result
         };
         responseConvert.Values.Add(convertResult);
         _logger.LogDebug("PdfController.Convert() OK");
         return(Ok(responseConvert));
     }
     catch (Exception e)
     {
         _logger.LogError(e.Message);
         return(BadRequest(e.Message));
     }
 }
Пример #2
0
        public ActionResult <ProcessResponse> Process(IFormFile file)
        {
            _logger.LogDebug($"Process response");
            ProcessResponse response      = new ProcessResponse();
            string          fileExtension = Path.GetExtension(file.FileName).Trim('.');

            try
            {
                using (Stream stream = file.OpenReadStream())
                {
                    if (file.Length == 0)
                    {
                        throw new Exception("Файл не может быть пуст");
                    }
                    if (CheckFileExtension.GetFileExtension(fileExtension) == FileExtension.Extensions.Unknown)
                    {
                        throw new Exception("Неподдерживаемый тип файла");
                    }
                    if (CheckFileExtension.GetFileExtension(fileExtension) == FileExtension.Extensions.Pdf)
                    {
                        ExtractTextFileResponse extractResult = _fileInfoPdf.Extract(stream);
                        PreviewFileResponse     previewResult = _fileInfoPdf.Preview(stream, 0);
                        ProcessFileResponse     result        = new ProcessFileResponse {
                            Image = previewResult.Image, TextValues = extractResult.Values
                        };
                        response.Values.Add(result);
                        return(response);
                    }
                    else
                    {
                        byte[] resultPdf = _fileInfoPdf.Convert(stream, file.FileName);
                        using (Stream pdfStream = new MemoryStream(resultPdf))
                        {
                            ExtractTextFileResponse extractResult = _fileInfoPdf.Extract(pdfStream);
                            PreviewFileResponse     previewResult = _fileInfoPdf.Preview(pdfStream, 0);
                            ProcessFileResponse     result        = new ProcessFileResponse {
                                Name = file.FileName, Pdf = resultPdf, TextValues = extractResult.Values, Image = previewResult.Image
                            };
                            response.Values.Add(result);
                        }
                    }
                }
                _logger.LogDebug("PdfController.Process() OK");
                return(Ok(response));
            }
            catch (Exception e)
            {
                _logger.LogError(e.Message);
                return(BadRequest($"Ошибка обработки файла '{file.FileName}'. Фаил неизвестного формата или файл поврежден"));
            }
        }
Пример #3
0
        public byte[] Convert(Stream file, string fileName)
        {
            _logger.LogDebug($"Start convert file, check file extenstion");
            string ext = System.IO.Path.GetExtension(fileName).Trim('.');

            FileExtension.Extensions type = CheckFileExtension.GetFileExtension(ext);
            switch (type)
            {
            case FileExtension.Extensions.Doc:
            case FileExtension.Extensions.Rtf:
            case FileExtension.Extensions.Dot:
                return(WordToPdf(file));
            }
            _logger.LogDebug("FileInfoPDFService.Convert....OK");
            return(null);
        }
        public async Task <IActionResult> Upload(IFormFile file)
        {
            try
            {
                _log.LogDebug($"UploadFile file={file}");
                string fileExtension = Path.GetExtension(file.FileName).Trim('.');
                if (file == null || file.Length == 0)
                {
                    throw new Exception("Файл не может быть пуст");
                }
                if (CheckFileExtension.GetFileExtension(fileExtension) == FileExtension.Extensions.Unknown)
                {
                    throw new Exception("Неподдерживаемый тип файла");
                }
                string          currentSid = Utils.GetSid(HttpContext);
                Document        document   = new Document();
                PdfText         text       = null;
                ProcessResponse result;
                string          dirPdfPath  = Folder.GetAllPath(Path.Combine(Umk.IO.Folder.UploadsFolder, "pdf"));
                string          filePdfPath = Path.Combine(dirPdfPath, $"{Path.GetFileNameWithoutExtension(file.FileName)}.pdf");
                if (CheckFileExtension.GetFileExtension(fileExtension) == FileExtension.Extensions.Pdf)
                {
                    result = await SendToPdfService(file);

                    string documentId = Guid.NewGuid().ToString();
                    foreach (var infoPdf in result.Values)
                    {
                        document = new Document {
                            doc_id = documentId, parent_id = null, path = filePdfPath.Substring(filePdfPath.IndexOf("\\uploads") + 1), type = Convert.ToByte(CheckFileExtension.GetFileExtension("pdf")), upload_time_stamp = DateTime.Now, short_name = Path.GetFileNameWithoutExtension(filePdfPath), user_sid = currentSid, picture = "data:image/jpg;base64," + Convert.ToBase64String(infoPdf.Image)
                        };
                        _fileService.Add(document, file, filePdfPath, (f, ff) =>
                        {
                            using (var pdfFileStream = new FileStream(filePdfPath, FileMode.Create))
                            {
                                file.CopyTo(pdfFileStream);
                            }
                        });
                        foreach (var pdfText in infoPdf.TextValues)
                        {
                            text = new PdfText {
                                parent_id = documentId, page_number = pdfText.Key, page_text = pdfText.Value, short_name = document.short_name
                            };
                        }
                    }
                }
                else
                {
                    string dir        = Folder.GetAllPath(Path.Combine(Umk.IO.Folder.UploadsFolder, fileExtension));
                    string filePath   = Path.Combine(dir, file.FileName);
                    string documentId = Guid.NewGuid().ToString();
                    document = new Models.Document {
                        doc_id = documentId, parent_id = null, path = filePath.Substring(filePath.IndexOf("\\uploads") + 1), type = Convert.ToByte(CheckFileExtension.GetFileExtension(fileExtension)), upload_time_stamp = DateTime.Now, short_name = Path.GetFileNameWithoutExtension(filePath), user_sid = currentSid, picture = null
                    };
                    _fileService.Add(document, file, filePath, (f, ff) =>
                    {
                        using (var fileStream = new FileStream(filePath, FileMode.Create))
                        {
                            file.CopyTo(fileStream);
                        }
                    });
                    result = await SendToPdfService(file);

                    foreach (var infoPdf in result.Values)
                    {
                        document = new Models.Document {
                            doc_id = Guid.NewGuid().ToString(), parent_id = documentId, path = filePdfPath.Substring(filePdfPath.IndexOf("\\uploads") + 1), type = Convert.ToByte(CheckFileExtension.GetFileExtension("pdf")), upload_time_stamp = DateTime.Now, short_name = Path.GetFileNameWithoutExtension(filePdfPath), user_sid = currentSid, picture = "data:image/jpg;base64," + Convert.ToBase64String(infoPdf.Image)
                        };
                        _fileService.Add(document, file, filePdfPath, (f, ff) =>
                        {
                            using (var pdfFileStream = new FileStream(filePdfPath, FileMode.Create))
                                using (Stream streamPdf = new MemoryStream(infoPdf.Pdf))
                                {
                                    streamPdf.CopyTo(pdfFileStream);
                                }
                        });
                        foreach (var pdfText in infoPdf.TextValues)
                        {
                            text = new PdfText {
                                parent_id = documentId, page_number = pdfText.Key, page_text = pdfText.Value, short_name = document.short_name
                            };
                        }
                    }
                }
                _log.LogDebug("UploadDownloadController.Upload() OK");
                return(Ok(document));
            }
            catch (Exception e)
            {
                _log.LogError(e.Message);
                return(BadRequest(e.Message));
            }
        }