Пример #1
0
        public async Task <FileStorageInfo> SaveFileAsync(byte[] fileContents, string fileExtension, bool createThumbnial = false, string fileFriendlyName = null)
        {
            string          fileName    = fileFriendlyName ?? Path.GetRandomFileName();
            FileStorageInfo storageInfo = await SaveFileContent(fileContents,
                                                                fileName,
                                                                fileExtension.ToLower(),
                                                                createThumbnial,
                                                                fileFriendlyName);

            return(storageInfo);
        }
Пример #2
0
        public async Task <FileStorageInfo> SaveFileAsync(Stream stream, string fileExtension, bool createThumbnial = false, string fileFriendlyName = null)
        {
            string uniqueFileName = Path.GetRandomFileName();
            // string path = Path.Combine(StoreRoot, DateTime.Now.ToString("yyyyMMdd"), fileName);
            FileStorageInfo storageInfo = await SaveFileContent(stream,
                                                                uniqueFileName,
                                                                fileExtension.ToLower(),
                                                                createThumbnial,
                                                                fileFriendlyName);

            return(storageInfo);
        }
Пример #3
0
        public async Task <ActionResult> Post(bool thumbinal = false, bool forContent = false)
        {
            logger.LogDebug("Start FileController Post");
            // Check if the request contains multipart/form-data.
            if (!MultipartRequestHelper.IsMultipartContentType(Request.ContentType))
            {
                logger.LogError($"The request couldn't be processed (Error 1).");
                return(BadRequest($"The request couldn't be processed (Error 1)."));
            }

            try
            {
                var boundary = MultipartRequestHelper.GetBoundary(
                    MediaTypeHeaderValue.Parse(Request.ContentType),
                    _defaultFormOptions.MultipartBoundaryLengthLimit);
                var reader = new MultipartReader(boundary, HttpContext.Request.Body);

                List <ObjectFileField> files = new List <ObjectFileField>();
                var section = await reader.ReadNextSectionAsync();

                while (section != null)
                {
                    var hasContentDispositionHeader =
                        ContentDispositionHeaderValue.TryParse(
                            section.ContentDisposition, out var contentDisposition);

                    if (hasContentDispositionHeader)
                    {
                        if (MultipartRequestHelper
                            .HasFileContentDisposition(contentDisposition))
                        {
                            // Don't trust the file name sent by the client. To display
                            // the file name, HTML-encode the value.
                            var trustedFileNameForDisplay = WebUtility.HtmlEncode(
                                contentDisposition.FileName.Value);

                            logger.LogInformation("the raw file name is : " + trustedFileNameForDisplay);

                            var             extension     = Path.GetExtension(contentDisposition.FileName.Value);
                            long            fileSizeLimit = long.Parse(mConfiguration["SiteSettings:FileUpload:FileSizeLimit"]);
                            FileStorageInfo info          =
                                await storageService.SaveFileAsync(section.Body, extension, thumbinal, trustedFileNameForDisplay);

                            logger.LogDebug("file save path : " + info.FileUri);
                            //FileHelper.ProcessStreamedFile(section, contentDisposition,
                            //     _permittedExtensions, fileSizeLimit);

                            files.Add(new ObjectFileField()
                            {
                                FileName = trustedFileNameForDisplay,
                                //FileFullPath = info.FileUri,

                                FileUrl       = string.Format("/api/Files/DownloadFile/{0}/{1}", info.FileUniqueName, WebUtility.UrlEncode(trustedFileNameForDisplay)),
                                FileExtension = extension,
                                Updated       = info.LastUpdated,
                                Created       = info.Creation,
                                FileCRC       = info.CRC,
                                FileSize      = (int)(info.Size / 1024),
                            });


                            //only care about single document.
                            if (forContent)
                            {
                                break;
                            }
                        }

                        // Drain any remaining section body that hasn't been consumed and
                        // read the headers for the next section.
                        section = await reader.ReadNextSectionAsync();
                    }
                }

                //return the action result.
                ActionResult result = forContent ? this.Ok(new UploadFile()
                {
                    uploaded = 1, fileName = files[0].FileName, url = files[0].FileUrl
                })
                            : this.Ok(new { status = "success", files = files });

                logger.LogDebug("End FileController Post");
                return(result);
            }
            catch (Exception ex)
            {
                logger.LogError(ex.Message);
                return(BadRequest(ex.GetBaseException().Message));
            }
        }
        public ResponseModel UploadCustomerOrder(System.Web.HttpRequest httpRequest, string rootPath)
        {
            ResponseModel res = new ResponseModel();

            try
            {
                if (httpRequest.Files.Count > 0)
                {
                    foreach (string file in httpRequest.Files)
                    {
                        HttpPostedFile fileUploaded = httpRequest.Files[file];
                        string         fileName     = UtilityHelper.SaveUploadedFile(fileUploaded, rootPath);
                        string         filePath     = Path.Combine(rootPath, fileName);
                        if (fileName != "")
                        {
                            using (var reader = new StreamReader(filePath))
                                using (var csv = new CsvReader(reader))
                                {
                                    int rowCnt = 0;
                                    var record = new CustomerOrderModel();

                                    var records = csv.EnumerateRecords(record);

                                    using (CustomerDBEntities db = new CustomerDBEntities())
                                    {
                                        FileStorageInfo fileInfo = new FileStorageInfo();
                                        fileInfo.FileUploadId     = Guid.NewGuid();
                                        fileInfo.OriginalFileName = fileUploaded.FileName;
                                        fileInfo.StoredFileName   = fileName;
                                        fileInfo.CreatedDate      = DateTime.Now;
                                        db.FileStorageInfoes.Add(fileInfo);
                                        db.SaveChanges();

                                        foreach (var r in records)
                                        {
                                            TempCustomerOrder tmpOrder = new TempCustomerOrder();
                                            tmpOrder.ID               = Guid.NewGuid();
                                            tmpOrder.order_number     = r.order_number;
                                            tmpOrder.qty              = r.qty;
                                            tmpOrder.user_id          = r.user_id;
                                            tmpOrder.FileUploadedId   = fileInfo.FileUploadId;
                                            tmpOrder.CreatedDate      = DateTime.Now;
                                            tmpOrder.IsAddedToMainTbl = false;
                                            db.TempCustomerOrders.Add(tmpOrder);
                                            db.SaveChanges();

                                            rowCnt++;
                                        }
                                    }
                                    if (rowCnt > 0)
                                    {
                                        //Upsert Customer Order Data from Staginig table to Main Table
                                        res = UpsertOrderData();
                                        if (res.status)
                                        {
                                            res.status  = true;
                                            res.message = "File Upload Completed Successfully...!!!";
                                            res.data    = GetAllCustomerOrders();
                                        }
                                        return(res);
                                    }
                                    else
                                    {
                                        res.message = "No/Invalid Data in File...!!!";
                                        return(res);
                                    }
                                }
                        }
                    }
                }
                return(res);
            }
            catch (Exception ex)
            {
                if (ex.Source == "CsvHelper")
                {
                    res.message = "Invalid File Data...!!!";
                }
                else
                {
                    res.message = ex.Message;
                }
                res.data = ex.InnerException;
                return(res);
            }
        }
Пример #5
0
 Task IAsyncFileRepository <FileStorageInfo> .Upload(FileStorageInfo file, Stream stream)
 {
     throw new System.NotImplementedException();
 }