コード例 #1
0
ファイル: ImportFile.cs プロジェクト: ArjunBhalodiya/Stock
        public HttpStatusCode Upload(string securityID, FileUploadType fileType, HttpRequest httpRequest)
        {
            if (httpRequest.Files.Count != 1)
            {
                return(HttpStatusCode.BadRequest);
            }
            else
            {
                var postedFile = httpRequest.Files[0];
                if (FileHandling.IsCSV(postedFile.FileName))
                {
                    return(HttpStatusCode.BadRequest);
                }

                filePath = HttpContext.Current.Server.MapPath("~/" + postedFile.FileName);
                postedFile.SaveAs(filePath);

                if (ProcessFile(securityID, fileType))
                {
                    return(HttpStatusCode.OK);
                }

                return(HttpStatusCode.InternalServerError);
            }
        }
コード例 #2
0
        public async Task <IActionResult> UploadFile([FromForm] FileUploadType uploadType)
        {
            var filesCollection = this.HttpContext.Request.Form.Files;
            var uploadResult    = await this.contentService.UploadFile(filesCollection, uploadType);

            return(new JsonResult(uploadResult));
        }
コード例 #3
0
        private string GetPath(FileUploadType fileUploadType)
        {
            string contentRootPath = _env.WebRootPath;

            switch (fileUploadType)
            {
            case FileUploadType.UserImg:
                return(contentRootPath + "\\img\\members\\");
            }
            throw new Exception("cant create path");
        }
コード例 #4
0
        public async Task <string> GetFileName(Guid Id, FileUploadType fileUploadType, string filename)
        {
            switch (fileUploadType)
            {
            case FileUploadType.UserImg:
                return(GetUserImg(Id, Path.GetExtension(filename)));

            case FileUploadType.ProductImg:
                return(GetFilenameInner(Id, Path.GetExtension(filename)));
            }
            throw new Exception("no file upload type selected");
        }
コード例 #5
0
        private string GetBlobContainer(FileUploadType fileUploadType)
        {
            switch (fileUploadType)
            {
            case FileUploadType.UserImg:
                return("usrimg");

            case FileUploadType.ProductImg:
                return("productimg");
            }
            throw new Exception("Cant find container name");
        }
コード例 #6
0
        public ActionResult Index(string typecode, string details)
        {
            JsonResult result = new JsonResult();

            result.Data = new { success = 0 };

            // Get Upload Type
            FileUploadType uploadType = FileUploadType.Unknown;

            Enum.TryParse <FileUploadType>(typecode, out uploadType);

            string fileName    = Request.QueryString["filename"];
            string firstPart   = Request.QueryString["firstpart"];
            bool   isFirstPart = false;

            if (firstPart == "1")
            {
                isFirstPart = true;
            }

            Stream inputStream = Request.InputStream;

            switch (uploadType)
            {
            case FileUploadType.FlexPageImage:

                string[] detailParts = details.Split('/');
                if (detailParts.Length > 1)
                {
                    string categoryId  = detailParts[0];
                    string pageVersion = detailParts[1];

                    if (DiskStorage.UploadFlexPageImagePartial(MTApp.CurrentStore.Id, inputStream, fileName, isFirstPart, categoryId, pageVersion) == true)
                    {
                        result.Data = new { success  = "1",
                                            imageurl = DiskStorage.FlexPageImageUrl(MTApp, categoryId, pageVersion, fileName, false),
                                            filename = MerchantTribe.Web.Text.CleanFileName(fileName) };
                    }
                    else
                    {
                        result.Data = new { success  = "0",
                                            imageurl = DiskStorage.FlexPageImageUrl(MTApp, categoryId, pageVersion, string.Empty, false),
                                            filename = string.Empty };
                    }
                }
                break;
            }

            return(result);
        }
コード例 #7
0
        public static bool IsValidFile(this IFormFile file, FileUploadType fileType, bool isRequired = true)
        {
            if (!isRequired && file == null)
            {
                return(true);
            }

            if (file == null || file?.Length == 0)
            {
                return(false);
            }

            var           extension    = Path.GetExtension(file.FileName).Replace(".", "").ToLower();
            List <string> allowedTypes = fileType.GetDescription()?.Split(',')?.ToList() ?? new List <string>();

            return(allowedTypes.Any(x => x == extension));
        }
コード例 #8
0
ファイル: ContentService.cs プロジェクト: CeSiumUA/Doppler
        public async Task <Guid> UploadFile(IFormFileCollection files, FileUploadType uploadType)
        {
            Guid result = Guid.Empty;

            switch (uploadType)
            {
            case FileUploadType.ProfileImage:
                result = await this.repository.SetProfileImage(identityService.AuthenticatedUser,
                                                               files.FirstOrDefault());

                break;

            default:
                break;
            }
            return(result);
        }
コード例 #9
0
        public async Task Save(MemoryStream stream, string fileName, FileUploadType fileUploadType)
        {
            try
            {
                var path = GetPath(fileUploadType);

                string filename = path + fileName;

                FileStream writeStream = new FileStream(filename, FileMode.Create, FileAccess.Write);

                await ReadWriteStream(stream, writeStream);
            }
            catch (Exception e)
            {
                throw;
            }
        }
        public static IBlobImport Create(IFileUploadContext fileUploadContext, FileUploadType fileType, string storageAccountConnection)
        {
            var employerBlobStorage = new EmployerBlobStorage(storageAccountConnection);

            switch (fileType)
            {
            case FileUploadType.Employer:
                return(new EmployerBlobImport(new EmployerDataLoader(employerBlobStorage), new EmployerDataValidator()));

            case FileUploadType.Contact:
                return(new ContactBlobImport(new ContactDataLoader(employerBlobStorage), new ContactDataValidator()));

            case FileUploadType.Query:
                return(new QueryBlobImport(new QueryDataLoader(employerBlobStorage), new QueryDataValidator()));
            }

            throw new InvalidOperationException();
        }
コード例 #11
0
        public async Task UploadToStorage(string fileName, MemoryStream file, FileUploadType fileUploadType)
        {
            string connectionString = _storageOptions.ConnectionString;

            // Create a BlobServiceClient object which will be used to create a container client
            BlobServiceClient blobServiceClient = new BlobServiceClient(connectionString);

            var containerName = GetBlobContainer(fileUploadType);
            BlobContainerClient containerClient = blobServiceClient.GetBlobContainerClient(containerName);  // .CreateBlobContainerAsync(containerName);

            // Get a reference to a blob
            BlobClient blobClient = containerClient.GetBlobClient(fileName);

            // Open the file and upload its data
            //using FileStream uploadFileStream = File.OpenRead(localFilePath);
            await blobClient.UploadAsync(file);

            //uploadFileStream.Close();
        }
コード例 #12
0
        private static IAsyncCollector <string> GetQueueOutput(FileUploadType fileUploadType,
                                                               IAsyncCollector <string> employerOutput,
                                                               IAsyncCollector <string> contactOutput,
                                                               IAsyncCollector <string> queryOutput)
        {
            switch (fileUploadType)
            {
            case FileUploadType.Employer:
                return(employerOutput);

            case FileUploadType.Contact:
                return(contactOutput);

            case FileUploadType.Query:
                return(queryOutput);
            }

            throw new InvalidOperationException();
        }
コード例 #13
0
ファイル: ImportFile.cs プロジェクト: ArjunBhalodiya/Stock
        private bool ProcessFile(string securityID, FileUploadType fileType)
        {
            try
            {
                // Create connection to excel file
                ExcelQueryFactory connection = new ExcelQueryFactory(filePath);

                //Query a worksheet with a header row
                var rows = from row in connection.Worksheet(0)
                           select row;

                // Fill stock list
                foreach (var row in rows)
                {
                    var result = new StockPriceRepository().Add(new StockPriceVm
                    {
                        SecurityId     = securityID,
                        Date           = Convert.ToDateTime(row[0]),
                        Open           = Convert.ToDecimal(row[1]),
                        High           = Convert.ToDecimal(row[2]),
                        Low            = Convert.ToDecimal(row[3]),
                        Close          = Convert.ToDecimal(row[4]),
                        WAP            = Convert.ToDecimal(row[5]),
                        NoOfShares     = Convert.ToInt32(row[6]),
                        NoOfTrades     = Convert.ToInt32(row[7]),
                        TotalTurnOver  = Convert.ToInt32(row[8]),
                        DeliverableQty = Convert.ToInt32(row[9])
                    });

                    if (!result)
                    {
                        return(false);
                    }
                }

                return(true);
            }
            catch
            {
                return(false);
            }
        }
コード例 #14
0
        public string CheckExtension(string extension, FileUploadType fileUploadType)
        {
            switch (fileUploadType)
            {
            case FileUploadType.UserImg:
                if (extension != ".png" && extension != ".jpg" && extension != ".jpeg")
                {
                    return("file extension must be one of: png,jpg");
                }
                break;

            case FileUploadType.ProductImg:
                if (extension != ".png" && extension != ".jpg" && extension != ".jpeg")
                {
                    return("file extension must be one of: png,jpg");
                }
                break;
            }
            return(string.Empty);
        }
コード例 #15
0
        /// <summary>
        /// 取得FILEBASE
        /// </summary>
        /// <param name="ID"></param>
        /// <param name="actionName"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        public List <FileViewModel> GetFiles(int ID, string actionName, FileUploadType fileType = FileUploadType.NOTSET)
        {
            List <FileViewModel> fileList = new List <FileViewModel>();

            fileList = this.DB.FILEBASE
                       .Where(o => o.MAP_ID == ID &&
                              o.MAP_SITE.StartsWith(actionName) &&
                              o.FILE_TP == "F" &&
                              (fileType == FileUploadType.NOTSET ? true : o.IDENTIFY_KEY == (int)fileType)
                              )
                       .Select(s => new FileViewModel()
            {
                ID           = s.ID,
                FileName     = s.FILE_RANDOM_NM,
                RealFileName = s.FILE_REL_NM,
                FilePath     = s.FILE_PATH,
                FileUrl      = s.URL_PATH,
            })
                       .ToList();

            return(fileList);
        }
コード例 #16
0
        public async Task <SmFileUploadAuthorization> Authorize(FileUploadType type, string name, long size, DateTime lastModifiedDate)
        {
            var ttl            = TimeSpan.FromMinutes(_fileUploadSettings.ExpiryMinutes);
            var guid           = Guid.NewGuid();
            var path           = GenerateUploadPath(_fileUploadSettings.BucketName, _fileUploadSettings.PathTemplate, guid);
            var expirationDate = DateTime.UtcNow.AddMinutes(_fileUploadSettings.ExpiryMinutes);

            var url = _s3Client.GetPreSignedURL(new GetPreSignedUrlRequest
            {
                BucketName = path.BucketName,
                Key        = path.Key,
                Verb       = HttpVerb.PUT,
                Expires    = expirationDate
            });

            var entity = await _fileUploadRepository.Start(url, ttl, guid, type, name, size, lastModifiedDate);

            return(new SmFileUploadAuthorization
            {
                Url = url,
                Guid = entity.Guid,
                ExpirationDate = expirationDate
            });
        }
コード例 #17
0
        public static async Task OnMediaRequest(Microsoft.AspNetCore.Http.HttpContext e, E_RPWS_User user, WebPebbleProject proj)
        {
            //Get the request method
            RequestHttpMethod method = Program.FindRequestMethod(e);

            //Get the params
            string[] urlParams = Program.GetUrlPathRequestFromInsideProject(e);
            string   id        = urlParams[0];

            //If the ID is create, pass this request to the creation.
            if (id == "create")
            {
                await OnMediaCreateRequest(e, user, proj);

                return;
            }
            //Try to find the asset. It's ok if it doesn't exist.
            WebPebbleProjectAsset media = null;

            if (proj.media.ContainsKey(id))
            {
                media = proj.media[id];
            }
            //Decide what to do.
            //If it doesn't exist.
            if (media == null)
            {
                //Requesting a non-existing asset.
                await ThrowError(e, "This asset ID does not exist.", 1);

                return;
            }
            //Handle object editing (POST).
            if (method == RequestHttpMethod.post)
            {
                //Get the payload.
                MediaRequestPostPayload payload = Program.GetPostBodyJson <MediaRequestPostPayload>(e);
                //If a value isn't null, apply it.
                if (payload.name != null)
                {
                    media.nickname = payload.name;
                }
                if (payload.type != null)
                {
                    //Relocate
                    RelocateAsset(ref media, (ref WebPebbleProjectAsset m) =>
                    {
                        m.type = (AssetType)payload.type;
                    }, proj);
                }
                if (payload.sub_type != null)
                {
                    //Relocate
                    RelocateAsset(ref media, (ref WebPebbleProjectAsset m) =>
                    {
                        m.innerType = (InnerAssetType)payload.sub_type;
                    }, proj);
                }
                if (payload.filename != null)
                {
                    //Relocate
                    RelocateAsset(ref media, (ref WebPebbleProjectAsset m) =>
                    {
                        m.filename = WebPebbleProject.CreateSafeFilename(payload.filename);
                    }, proj);
                }
                if (payload.appinfoData != null)
                {
                    //Modify the appinfo data and set it on the PebbleProject.
                    SaveOutsideAppinfoJsonOnAsset(media, payload.appinfoData, proj);
                }
                //Save
                proj.media[id] = media;
                proj.SaveProject();
                await Program.QuickWriteJsonToDoc(e, media);

                return;
            }
            //Handle object uploading.
            if (method == RequestHttpMethod.put)
            {
                //Check the upload type in the query.
                FileUploadType uploadType = Enum.Parse <FileUploadType>(e.Request.Query["upload_method"]);
                Stream         source;
                int            length;
                if (uploadType == FileUploadType.Binary)
                {
                    //Read body directly
                    length = (int)e.Request.ContentLength;
                    source = e.Request.Body;
                }
                else
                {
                    //This is sent from the uploader in the interface.
                    //Get the file uploaded.
                    var f = e.Request.Form.Files["data"];
                    //Check if the file is valid.
                    if (f == null)
                    {
                        //No file uploaded.
                        await Program.QuickWriteJsonToDoc(e, new PutRequestReply
                        {
                            ok             = false,
                            size           = -1,
                            uploader_error = $"No file was uploaded."
                        });

                        return;
                    }
                    //Set
                    source = f.OpenReadStream();
                    length = (int)f.Length;
                }
                //Check if a file is too large.
                if (length > MAXIMUM_UPLOADED_SIZE)
                {
                    //Yup. Stop.
                    source.Close();
                    await Program.QuickWriteJsonToDoc(e, new PutRequestReply
                    {
                        ok             = false,
                        size           = length,
                        uploader_error = $"Your file is too powerful! The maximum filesize is {MAXIMUM_UPLOADED_SIZE_NAME} ({MAXIMUM_UPLOADED_SIZE.ToString()} bytes)."
                    });
                }
                //Remove an existing file if it exists.
                if (File.Exists(media.GetAbsolutePath(proj.projectId)))
                {
                    File.Delete(media.GetAbsolutePath(proj.projectId));
                }
                //Save
                using (FileStream fs = new FileStream(media.GetAbsolutePath(proj.projectId), FileMode.CreateNew))
                    await source.CopyToAsync(fs);
                //Tell the user it is ok
                await Program.QuickWriteJsonToDoc(e, new PutRequestReply
                {
                    ok             = true,
                    size           = length,
                    uploader_error = null
                });

                return;
            }
            //Handle object downloading
            if (method == RequestHttpMethod.get)
            {
                //Check if the file has been created yet
                string path = media.GetAbsolutePath(proj.projectId);
                if (!File.Exists(path))
                {
                    await ThrowError(e, "This asset exists, but has not been uploaded yet.", 4);

                    return;
                }
                //Get the MIME type from the query.
                if (!e.Request.Query.ContainsKey("mime"))
                {
                    //Assume we are querying the information.
                    await Program.QuickWriteJsonToDoc(e, media);

                    return;
                }
                //Set content type.
                e.Response.ContentType = e.Request.Query["mime"];
                //Set no-cache headers
                e.Response.Headers.Add("Cache-Control", "no-cache, no-store, must-revalidate");
                //Just load the data and copy it to the output stream.
                using (FileStream fs = new FileStream(path, FileMode.Open)) {
                    e.Response.ContentLength = fs.Length;
                    e.Response.StatusCode    = 200;
                    await fs.CopyToAsync(e.Response.Body);
                }
                return;
            }
            //Handle object deleting
            if (method == RequestHttpMethod.delete)
            {
                //Delete the file if it exists.
                string path = media.GetAbsolutePath(proj.projectId);
                if (File.Exists(path))
                {
                    File.Delete(path);
                }
                //Delete in appinfo.json.
                DeleteOutsideAppinfoJsonOnAsset(media.id, proj);
                //Delete
                proj.media.Remove(media.id);
                proj.SaveProject();
                //Tell the user it is ok
                await WriteOkReply(e);

                return;
            }
            //Unknown.
            await ThrowError(e, $"Invalid method for requesting media '{media.id}'.", 5);
        }