Пример #1
0
        public override Task ExecutePostProcessingAsync()
        {
            foreach (var fileData in FileData)
            {
                var fileName = Path.GetFileName(fileData.Headers.ContentDisposition.FileName.Trim('"'));
                var blobContainer = BlobHelper.GetBlobContainer();
                var blob = blobContainer.GetBlockBlobReference(fileName);

                blob.Properties.ContentType = fileData.Headers.ContentType.MediaType;

                using (var fs = File.OpenRead(fileData.LocalFileName))
                {
                    blob.UploadFromStream(fs);
                }

                // Delete local file from disk
                File.Delete(fileData.LocalFileName);

                var fileUpload = new FileUploadModel
                {
                    FileName = blob.Name,
                    FileUrl = blob.Uri.AbsoluteUri,
                    FileSizeInBytes = blob.Properties.Length
                };

                // Add uploaded blob to the list
                Uploads.Add(fileUpload);
            }

            return base.ExecutePostProcessingAsync();
        }
Пример #2
0
        public IActionResult Post(FileUploadModel model)
        {
            if (new FileExtensionContentTypeProvider().TryGetContentType(model.FileName, out var contentType))
            {
                // This is the point where we should persist the image bytes to a persistent store.
                // This could be anything from storing the image in a database (MySql, SqlServer), disk,
                // or object store (Amazon S3, Azure Blog Storage, Digital Ocean Spaces)

                // Once the image is stored, we'll want to return the url of where the image is stored
                // in the response. For the time being, this image url will be hardcoded so that the
                // TinyMCE editor functions.
                string imageUrl = "https://dustyhoppe-blog-images-prod.sfo2.cdn.digitaloceanspaces.com/cat-image-qf76g35k.jpg";
                return(Ok(new { imageUrl }));
            }

            return(UnprocessableEntity(new { Message = $"Cannot determine content type for file '{model.FileName}'." }));
        }
Пример #3
0
        /**
         * This scenario demonstrates the creation of a document with description
         *
         */
        public override async Task RunAsync()
        {
            // 1. The file's bytes must be read by the application and uploaded
            var filePath    = "sample.pdf";
            var fileName    = Path.GetFileName(filePath);
            var file        = File.ReadAllBytes(filePath);
            var uploadModel = await SignerClient.UploadFileAsync(fileName, file, "application/pdf");

            // 2. Define the name of the document which will be visible in the application
            var fileUploadModel = new FileUploadModel(uploadModel)
            {
                DisplayName = "One Description Sample"
            };

            // 3. For each participant on the flow, create one instance of ParticipantUserModel
            var participantUser = new ParticipantUserModel()
            {
                Name       = "Jack Bauer",
                Email      = "*****@*****.**",
                Identifier = "75502846369"
            };

            // 4. Create a FlowActionCreateModel instance for each action (signature or approval) in the flow.
            var flowActionCreateModel = new FlowActionCreateModel()
            {
                Type = FlowActionType.Signer,
                User = participantUser
            };

            // 5. Send the document create request writing the description as a string
            var documentRequest = new CreateDocumentRequest()
            {
                Files = new List <FileUploadModel>()
                {
                    fileUploadModel
                },
                Description = "Some Description Sample",
                FlowActions = new List <FlowActionCreateModel>()
                {
                    flowActionCreateModel
                }
            };
            var result = (await SignerClient.CreateDocumentAsync(documentRequest)).First();

            System.Console.WriteLine($"Document {result.DocumentId} created");
        }
        public IStoredFile StoreFile(FileUploadModel fileUploadModel, Guid formId)
        {
            var fileBase   = fileUploadModel.File;
            var filePath   = FolderBuilder.BuildFolder(Folder, fileUploadModel, formId);
            var fileName   = $"{Guid.NewGuid().ToString()}{Path.GetExtension(fileBase.FileName)}";
            var file       = UploadFile(fileBase, Path.Combine(filePath, fileName));
            var storedFile = new StoredFile
            {
                Url = file.ToString(),
                OriginalFileName = fileBase.FileName,
                ContentType      = fileBase.ContentType,
                ContentLength    = fileBase.ContentLength,
                StoredFileName   = fileName,
                StoredFilePath   = filePath
            };

            return(storedFile);
        }
        public bool AddUpdateBranch(FileUploadModel fileUploadModel)
        {
            tblFileUpload tblFileUpload = new tblFileUpload();

            if (fileUploadModel.File != null)
            {
                tblFileUpload.FileName = SaveFile(fileUploadModel);
            }

            if (!string.IsNullOrEmpty(tblFileUpload.FileName))
            {
                tblFileUpload.CreatedDate = DateTime.Now;
                _context.tblFileUpload.Add(tblFileUpload);
                _context.SaveChanges();
                return(true);
            }
            return(false);
        }
Пример #6
0
        public DocumentModel Create(int businessId, FileUploadModel document, bool visibleToAll = false, List <int> employeeGroups = null)
        {
            var result = ApiFileRequest <List <DocumentModel> >(string.Format("/business/{0}/document?visibleToAll={1}", businessId, visibleToAll), document);

            if (employeeGroups == null || !employeeGroups.Any())
            {
                return(result != null?result.FirstOrDefault() : null);
            }

            if (result == null || result.FirstOrDefault() == null)
            {
                return(null);
            }

            var id = result.First().Id;

            return(ApiRequest <DocumentModel, dynamic>(string.Format("/business/{0}/document", businessId), new { id, visibleToAll, employeeGroups }, Method.PUT));
        }
Пример #7
0
        /// <summary>
        /// 更新和新增文件上传
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public FileUploadModel InsertOrUpdateFileUpload(FileUploadModel input)
        {
            try
            {
                //var entObj =input.MapTo<FileUpload>();
                var entObj = _FileUploadCase.GetAll().FirstOrDefault(x => x.Id == input.Id) ?? new FileUpload();
                entObj = Fun.ClassToCopy(input, entObj, (new string[] { "Id" }).ToList());
                //var entObj= AutoMapper.Mapper.Map<FileUpload>(input);
                var id = _FileUploadCase.InsertOrUpdateAndGetId(entObj);

                return(entObj.MapTo <FileUploadModel>());
            } catch (Exception ex)
            {
                return(null);

                throw ex;
            }
        }
Пример #8
0
        public void DeleteFile(string filename)
        {
            if (filename != null)
            {
                var path = Path.Combine(Directory.GetCurrentDirectory(), Constants.StoragePath, filename);

                File.Delete(path);
                Startup.fileUploadModels.RemoveAll(f => f.FileName == filename);

                using (var ctx = new FileUploadContext())
                {
                    FileUploadModel file = ctx.Files.Where(f => f.FileName == filename).FirstOrDefault();

                    ctx.Files.Remove(file);
                    ctx.SaveChanges();
                }
            }
        }
        public ActionResult Add(int ContactFormID)
        {
            var model = new FileUploadModel
            {
                ParentID  = ContactFormID,
                MediaData = null
            };

            if (Request != null)
            {
                if (Request.Files.Count > 0)
                {
                    if (string.IsNullOrWhiteSpace(Path.GetFileName(Request.Files[0].FileName)))
                    {
                        _notifier.Error(T("Please select a file."));
                    }
                    else
                    {
                        ContactFormRecord contactForm = _contactFormService.GetContactForm(ContactFormID);

                        var folderPath = contactForm.PathUpload;
                        for (int i = 0; i < Request.Files.Count; i++)
                        {
                            var file     = Request.Files[i];
                            var filename = Path.GetFileName(file.FileName);

                            if (_contactFormService.FileAllowed(filename))
                            {
                                var mediaPart = _mediaLibraryService.ImportMedia(file.InputStream, folderPath, filename);
                                _contentManager.Create(mediaPart);
                                var fullPart = _contentManager.Get(mediaPart.Id).As <MediaPart>();
                                model.MediaData = fullPart;
                            }
                            else
                            {
                                _notifier.Error(T("The file extension in the filename is not allowed or has not been provided."));
                            }
                        }
                    }
                }
            }

            return(View(model));
        }
Пример #10
0
        public bool Upload(FileUploadModel file)
        {
            var status = database.Statuses.Get(x => x.Title == "Closed").Result;
            var user   = database.Users.Get(x => x.IdenityId == file.UserId).Result;

            if (user == null)
            {
                throw new UserServiceException("User wasn't found");
            }
            var ex = System.IO.Path.GetExtension(file.File.FileName);

            var type = database.Types.Get(x => x.Format == ex).Result;

            if (type == null)
            {
                type = new DAL.Models.CommonModels.Type
                {
                    Format = ex
                };
            }


            var path = FileManagment.GeneratePath(file);



            var file_tosave = new File()
            {
                Status      = status,
                Description = file.Description,
                User        = user,
                Name        = file.Name,
                Type        = type,
                Path        = new DAL.Models.CommonModels.Path()
                {
                    Link = path.Path
                }
            };

            database.Files.Create(file_tosave);
            database.Save();
            return(true);
        }
Пример #11
0
        public ActionResult PrepareMetadata(int blocksCount, string fileName, long fileSize)
        {
            var container = CloudStorageAccount.Parse(ConfigurationManager.AppSettings[Constants.ConfigurationSectionKey]).CreateCloudBlobClient().GetContainerReference(Constants.ContainerName);

            container.CreateIfNotExist();
            var fileToUpload = new FileUploadModel()
            {
                BlockCount          = blocksCount,
                FileName            = fileName,
                FileSize            = fileSize,
                BlockBlob           = container.GetBlockBlobReference(fileName),
                StartTime           = DateTime.Now,
                IsUploadCompleted   = false,
                UploadStatusMessage = string.Empty
            };

            Session.Add(Constants.FileAttributesSession, fileToUpload);
            return(Json(true));
        }
Пример #12
0
 public async Task <ResultBean> uploadFile([FromForm] FileUploadModel fm)
 {
     if (fm.file.Length > 0)
     {
         var filePath = combineDrivePath(fm.driveId, fm.pathToDrive) + "/" + fm.file.FileName;
         using (var fileStream = new FileStream(filePath, FileMode.Create))
         {
             try
             {
                 await fm.file.CopyToAsync(fileStream);
             }
             catch (Exception e)
             {
                 return(ResultBean.Error("保存失败"));
             }
         }
     }
     return(ResultBean.Success());
 }
Пример #13
0
        public async Task <string> UploadFile(FileUploadModel File, string StorageConnectionString)
        {
            if (CloudStorageAccount.TryParse(StorageConnectionString, out CloudStorageAccount storageAccount))
            {
                CloudBlobClient    cloudBlobClient    = storageAccount.CreateCloudBlobClient();
                CloudBlobContainer cloudBlobContainer = cloudBlobClient.GetContainerReference(File.FileFormat.ToString().ToLower());
                await cloudBlobContainer.CreateIfNotExistsAsync();

                CloudBlockBlob cloudBlockBlob = cloudBlobContainer.GetBlockBlobReference(File.FileName);
                var            FileBytes      = Convert.FromBase64String(File.FileBytes);
                await cloudBlockBlob.UploadFromByteArrayAsync(FileBytes, 0, FileBytes.Length);

                return(cloudBlockBlob.Uri.ToString());
            }
            else
            {
                return("Something went wrong");
            }
        }
Пример #14
0
        /// <summary>
        /// 通过自增id获取文件信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        internal FileUploadModel GetFileById(int id)
        {
            string sql = @"SELECT [id]
      ,[OrigenalName]
      ,[relativepath]
      ,[savepath]
      ,[extentionname]
      ,[type]
      ,[objid]
      ,[objtype]
      ,[creator]
      ,[creationip]
  FROM [EtownDB].[dbo].[fileupload] f WHERE f.Id=@id";
            var    cmd = sqlHelper.PrepareTextSqlCommand(sql);

            cmd.AddParam("@id", id);

            FileUploadModel file = null;

            using (var reader = cmd.ExecuteReader())
            {
                if (reader.Read())
                {
                    file = new FileUploadModel()
                    {
                        Id            = reader.GetValue <int>("id"),
                        OrigenalName  = reader.GetValue <string>("OrigenalName"),
                        Relativepath  = reader.GetValue <string>("relativepath") == "" ? "Default.jpg" : reader.GetValue <string>("relativepath"),
                        Savepath      = reader.GetValue <string>("savepath"),
                        Extentionname = reader.GetValue <string>("extentionname"),
                        Type          = reader.GetValue <int>("type"),
                        Objid         = reader.GetValue <int>("objid"),
                        Objtype       = reader.GetValue <int>("objtype"),
                        Creator       = reader.GetValue <string>("creator"),
                        Creationip    = reader.GetValue <string>("creationip")
                    };
                }
            }
            //sqlHelper.Commit();
            //sqlHelper.Dispose();
            return(file);
        }
Пример #15
0
        private static List <FileUploadModel> GetFiles()
        {
            List <FileUploadModel> files = new List <FileUploadModel>();

            List <FileUploadModel> fileUploads;

            using (var ctx = new FileUploadContext())
            {
                fileUploads = ctx.Files.AsEnumerable <FileUploadModel>().ToList();
            }

            string[] filesInDir = Directory.GetFiles("FileStorage");

            if (filesInDir.Length > 0)
            {
                foreach (string file in filesInDir)
                {
                    FileUploadModel fileUpload;

                    string fileName = file.Split('\\')[1];

                    if (fileUploads.Any(f => f.FileName == fileName))
                    {
                        fileUpload = fileUploads.Where(f => f.FileName == fileName).FirstOrDefault();
                    }
                    else
                    {
                        fileUpload = new FileUploadModel()
                        {
                            Id         = Guid.NewGuid(),
                            Author     = "System",
                            FileName   = fileName,
                            Created_At = DateTime.Now,
                            Downloads  = 0
                        };
                    }

                    files.Add(fileUpload);
                }
            }
            return(files);
        }
 public async Task <ImageResponse> SaveImage([FromForm] FileUploadModel uploadObj)
 {
     try
     {
         if (uploadObj.files.Length > 0)
         {
             if (!Directory.Exists(_environment.ContentRootPath + "\\wwwroot\\images\\"))
             {
                 Directory.CreateDirectory(_environment.ContentRootPath + "\\wwwroot\\images\\");
             }
             using (FileStream fileStream = System.IO.File.Create(_environment.ContentRootPath + "\\wwwroot\\images\\" + uploadObj.files.FileName))
             {
                 uploadObj.files.CopyTo(fileStream);
                 fileStream.Flush();
                 ImageResponse imageResponse = new ImageResponse
                 {
                     ImageURL = "/images/" + uploadObj.files.FileName
                 };
                 return(imageResponse);
             }
         }
         else
         {
             List <string> Msg = new List <string>();
             Msg.Add("Unsuccessfully Image Uploaded!");
             ImageResponse imageResponse = new ImageResponse
             {
                 Messages = Msg
             };
             return(imageResponse);
         }
     }catch (Exception ex)
     {
         List <string> Msg = new List <string>();
         Msg.Add(ex.Message.ToString());
         ImageResponse imageResponse = new ImageResponse
         {
             Messages = Msg
         };
         return(imageResponse);
     }
 }
Пример #17
0
        public ServiceResult <Guid> Upload(FileUploadModel model)
        {
            var resultData = new ServiceResult <Guid>();

            try
            {
                if (!ModelState.IsValid)
                {
                    resultData.Code = MISSING_REQUIRED_FIELDS;
                    foreach (string error in ModelState.Values.SelectMany(v => v.Errors.Select(b => b.ErrorMessage)))
                    {
                        resultData.Message += error + Environment.NewLine;
                    }

                    return(resultData);
                }

                var file = new File
                {
                    FileName  = model.FileName,
                    FileType  = model.FileType,
                    Timestamp = DateTime.Now
                };

                new FileComponent().Create(file, model.File);

                resultData.Data = file.Id;
                resultData.Success();
            }
            catch (CommonException exception)
            {
                _log.Error(exception);
                resultData.SystemError(exception);
            }
            catch (Exception ex)
            {
                _log.Error(ex);
                resultData.SystemError(ex);
            }

            return(resultData);
        }
Пример #18
0
        public async Task <bool> FileUploadSave(FileUploadViewModel model)
        {
            try
            {
                if (model.UploadedFile == null || model.UploadedFile.Length == 0)
                {
                    return(false);
                }

                Guid   guid      = Guid.NewGuid();
                string directory = $"wwwroot\\images\\{guid.ToString()}";
                string path      = Path.Combine(
                    $"wwwroot\\images\\{guid.ToString()}", model.UploadedFile.FileName);

                string imageUrl = Path.Combine($"images\\{ guid.ToString()}", model.UploadedFile.FileName);

                if (!Directory.Exists(directory))
                {
                    Directory.CreateDirectory(directory);
                }

                using (var stream = new FileStream(path, FileMode.Create))
                {
                    await model.UploadedFile.CopyToAsync(stream);
                }

                FileUploadModel m = new FileUploadModel
                {
                    FileName = model.FileName,
                    FilePath = imageUrl
                };

                _baseRepsitory.Save(m);

                return(true);
            }
            catch (Exception ex)
            {
            }

            return(false);
        }
        public async Task <IActionResult> Upload([FromForm] FileUploadModel uploadInfo)
        {
            Console.WriteLine($"Upload: Key = {uploadInfo.Key}, Path = {uploadInfo.Path}, Name = {uploadInfo.Name}, Session = {uploadInfo.SessionId}");

            // upload to temp folder - maintaining folder structure
            if (uploadInfo.File != null)
            {
                var folderPath = string.IsNullOrWhiteSpace(uploadInfo.Path.TrimStart('/'))
                                        ? "C:\\Temp\\Uploads"
                                        : Path.Combine("C:\\Temp\\Uploads", uploadInfo.Path.TrimStart('/').Replace('/', System.IO.Path.DirectorySeparatorChar));
                if (!Directory.Exists(folderPath))
                {
                    Directory.CreateDirectory(folderPath);
                }
                var filePath = Path.Combine(folderPath, uploadInfo.Name);
                using var stream = System.IO.File.Create(filePath);
                await uploadInfo.File.CopyToAsync(stream);
            }
            return(Ok());
        }
Пример #20
0
        public ActionResult Index(FileUploadModel fileUploadModel)
        {
            if (fileUploadModel?.File == null || fileUploadModel.File.ContentLength <= 0)
            {
                return(HandleError("You need to click Choose File first, then Submit."));
            }

            var result = _csvFileHandler.ParseCsvFile(fileUploadModel.File, fileUploadModel.ContainsHeader);

            if (!result.Success)
            {
                return(HandleError(result.ErrorMessage));
            }

            return(View("FormattedDisplay", new FormattedDisplayModel
            {
                OriginalFileName = fileUploadModel.File.FileName,
                CsvTable = result.ParsedCsvContent
            }));
        }
        public HttpResponseMessage UploadImg([FromBody] UploadImgRequest request)
        {
            UploadFileResult viewModel = new UploadFileResult();

            if (!ModelState.IsValid)
            {
                viewModel.ResultCode = -100;
                string msg = ModelState.Values.Where(a => a.Errors.Count == 1).Aggregate(string.Empty, (current, a) => current + (a.Errors[0].ErrorMessage + ";"));
                viewModel.Message = "输入参数错误," + msg;
                return(viewModel.ResponseToJson());
            }
            try
            {
                string source   = request.baseContent;
                string base64   = source.Substring(source.IndexOf(',') + 1);
                byte[] data     = Convert.FromBase64String(base64);
                var    versions = new Dictionary <string, string>();
                versions.Add("_small", "maxwidth=50&maxheight=50&format=jpg");
                versions.Add("_medium", "maxwidth=200&maxheight=200&format=jpg");
                versions.Add("_large", "maxwidth=800&maxheight=660&format=jpg");
                var fileUploadModel = new FileUploadModel
                {
                    FileName   = "xxxxx.jpg",
                    VersionKey = versions
                };
                //上传图片至服务器
                var      dw      = new DynamicWebService();
                object[] postArg = new object[2];
                postArg[0] = fileUploadModel.ToJson();
                postArg[1] = data;
                var ret = dw.InvokeWebservice(
                    imageUpload + "/fileuploadcenter.asmx", "BiHuManBu.ServerCenter.FileUploadCenter", "FileUploadCenter", "ImageUpload", postArg);
                viewModel = ret.ToString().FromJson <UploadFileResult>();
            }
            catch (Exception)
            {
                viewModel.ResultCode = -100;
                viewModel.Message    = "图片上传异常";
            }
            return(viewModel.ResponseToJson());
        }
Пример #22
0
        public async Task <IActionResult> OnGetAsync()
        {
            var accessToken = await HttpContext.GetTokenAsync("access_token");

            FileUploadModel = new FileUploadModel();

            if (!await _apiHelper.AuthCheck(accessToken, User.FindFirst("sub").Value))
            {
                return(RedirectToPage("/Logout"));
            }

            if (!string.IsNullOrWhiteSpace(Id))
            {
                if (Guid.TryParse(Id, out Guid parsedId))
                {
                    if (parsedId != Guid.Empty)
                    {
                        var response = await _apiHelper.MakeAPICallAsync(accessToken, HttpMethod.Get, APITypes.FILE, $"File/{parsedId}");

                        if (response.StatusCode == System.Net.HttpStatusCode.OK)
                        {
                            FileUploadModel.FileHeader = response.ContentAsType <FileHead>();
                        }
                    }
                    else
                    {
                        if (!string.IsNullOrWhiteSpace(linkId) && !string.IsNullOrWhiteSpace(linkType))
                        {
                            FileUploadModel.linkId   = Guid.Parse(linkId);
                            FileUploadModel.linkType = linkType;
                        }
                    }
                }
            }

            await PageConstructor(SaveStates.IGNORE, accessToken);

            SaveMessageModel = await _apiHelper.GenerateSaveMessageModel(accessToken);

            return(Page());
        }
        public ActionResult Create([Bind(Include = "id,FileName,FilePath")] FileUploadModel fileUploadModel, HttpPostedFileBase fileupload1)
        {
            //if (ModelState.IsValid)
            //{
            //    db.FileUploadModels.Add(fileUploadModel);
            //    db.SaveChanges();
            //    return RedirectToAction("Index");
            //}


            string filename = string.Empty;
            string filepath = string.Empty;

            if (ModelState.IsValid)
            {
                filename = fileupload1.FileName;
                string ext = Path.GetExtension(filename);

                if (ext == ".jpg" || ext == ".png")
                {
                    filepath = Server.MapPath("~//Files//");
                    fileupload1.SaveAs(filepath + filename);
                    // FileUploadModel fm = new FileUploadModel();
                    fileUploadModel.FileName = filename;
                    fileUploadModel.FilePath = "~//Files//";

                    db.FileUploadModels.Add(fileUploadModel);
                    db.SaveChanges();
                }
                else
                {
                    return(Content("You can upload only jpg or png file"));
                }
            }
            else
            {
                return(Content("You can upload only jpg or png file"));
            }

            return(RedirectToAction("Index"));
        }
Пример #24
0
        public ActionResult UploadFile(HttpPostedFileBase file)
        {
            FileUploadModel fileModel = new FileUploadModel
            {
                Uploaded = false,
                Leader   = null,
                Message  = "File upload failed"
            };

            try
            {
                if (file == null)
                {
                    fileModel.Message = "No File Specified!";
                }
                else if (Path.GetExtension(file.FileName).ToLower() != ".csv")
                {
                    fileModel.Message = "File must be a CSV file!";
                }
                else if (file.ContentLength <= 0)
                {
                    fileModel.Message = "File is empty!";
                }
                else
                {
                    //Save the file
                    string saveLocation = Path.Combine(Server.MapPath("~/uploads"), file.FileName);
                    file.SaveAs(saveLocation);

                    fileModel.Message  = "File Upload Complete!";
                    fileModel.Uploaded = true;
                    fileModel.Leader   = LeaderClass.GetLeader(saveLocation);
                }
            }
            catch (Exception ex)
            {
                fileModel.Message = $"File Upload Failed {ex.Message}";
            }

            return(View("Upload", fileModel));
        }
Пример #25
0
        private async Task SendPartialFileAsync(Stream input, int position, string partialFileName, int nodeIndex, int bufferSize)
        {
            byte[] buffer = new byte[bufferSize];
            input.Read(buffer, position, bufferSize);
            var             client          = new RestClient(_globalVariables.SlaveNodeEndpoints[nodeIndex] + _globalVariables.SaveFileAPIRoute);
            FileUploadModel fileUploadModel = new FileUploadModel(partialFileName, buffer);
            var             request         = new RestRequest(Method.POST);

            request.AddJsonBody(fileUploadModel);
            request.AddHeader("cache-control", "no-cache");
            IRestResponse response = await client.ExecuteTaskAsync(request);

            if (response.StatusCode == HttpStatusCode.OK && JsonConvert.DeserializeObject <string>(response.Content) == "Success")
            {
                Console.WriteLine($"File piece {partialFileName} upload to slave node {nodeIndex} successfully!");
            }
            else
            {
                throw new Exception($"File piece {partialFileName} did not upload to slave node {nodeIndex} successfully!");
            }
        }
Пример #26
0
        public JsonResult ImageUpload(FileUploadModel model)
        {
            var file = model.ImageFile;

            if (file != null)
            {
                var fileName  = Path.GetFileName(file.FileName);
                var extention = Path.GetExtension(file.FileName);
                var filenamewithoutextension = Path.GetFileNameWithoutExtension(file.FileName);
                file.SaveAs(Server.MapPath("/Assets/Client/Img/Enterprise/LogoEnterprise/" + fileName));
                return(Json(new
                {
                    status = true,
                    srcImage = "/Assets/Client/Img/Enterprise/LogoEnterprise/" + fileName
                }));
            }
            return(Json(new
            {
                status = false
            }));
        }
Пример #27
0
        public FileUploadModel GetFileUploadByFileDescriptorId(String fileDescriptorId)
        {
            FileUploadModel result = null;

            lock (lockFiles)
            {
                if (FileFullPathByFileDescriptorId.ContainsKey(fileDescriptorId))
                {
                    String fullPath = FileFullPathByFileDescriptorId[fileDescriptorId];
                    if (FilesByFullPath.ContainsKey(fullPath))
                    {
                        result = FilesByFullPath[fullPath];
                    }
                    else
                    {
                        FileFullPathByFileDescriptorId.Remove(fileDescriptorId);
                    }
                }
            }
            return(result);
        }
        public async Task <bool> WriteFileAsync(Stream stream, FileUploadModel fileUploadModel)
        {
            var folderPath = Path.Combine(_configuration.GetValue <string>(AppSettings.FolderPath), fileUploadModel.FileType.ToString());

            if (!Directory.Exists(folderPath))
            {
                Directory.CreateDirectory(folderPath);
            }

            string fullPath = Path.Combine(folderPath, (fileUploadModel.FileName + fileUploadModel.Extension));

            stream.Position = 0;
            using (var fileStream = new FileStream(fullPath, FileMode.CreateNew))
            {
                await stream.CopyToAsync(fileStream);

                fileStream.Close();
            }

            return(true);
        }
Пример #29
0
        public string UpImageToCDN(HttpPostedFileBase uploadImage)
        {
            try
            {
                FileUploadModel model = new FileUploadModel();
                model.FileName = uploadImage.FileName;
                model.FileType = uploadImage.ContentType;
                byte[] buffer = new byte[uploadImage.ContentLength];
                uploadImage.InputStream.Read(buffer, 0, uploadImage.ContentLength);
                model.File = buffer;

                fileId = new BLL.BlobBLL().UploadImage(model);
                return(fileId);
            }
            catch (Exception ex)
            {
                log4net.ILog log = log4net.LogManager.GetLogger(typeof(FileUploader));
                log.Error(ex);
                return(null);
            }
        }
        public async Task <bool> UploadAndImportFile(int periodId, Stream stream, string fileName, int userId)
        {
            var randomFileName  = Guid.NewGuid().ToString();
            var fileUploadModel = new FileUploadModel
            {
                FileName  = randomFileName,
                FileType  = Shared.Enum.FileType.UploadDocument,
                Extension = Path.GetExtension(fileName),
                PeriodId  = periodId,
                UserId    = userId
            };

            var fileUploadSuccess = await _fileAccessor.WriteFileAsync(stream, fileUploadModel);

            if (fileUploadSuccess)
            {
                await _importProcess.ProcessFileAsync(fileUploadModel);
            }

            return(true);
        }
Пример #31
0
        public async Task <string> FileRemove(string File_Id) // 刪除上傳檔案
        {
            string DeleteResult = string.Empty;

            #region 確認資料庫是否有資料

            FileUploadModel file = await GetFileById(File_Id);

            if (file == null)
            {
                return("資料庫無此檔案");
            }
            #endregion

            #region 刪除 Server中的檔案

            var addUrl = file.FileUrl;
            if (System.IO.File.Exists(addUrl))
            {
                System.IO.File.Delete(addUrl);
            }
            #endregion

            #region 資料庫刪除處理

            try
            {
                // 刪除檔案
                _context.FileUpload.Remove(_context.FileUpload.SingleOrDefault(d => d.File_Id.Equals(File_Id)));
                // 儲存資料庫變更
                await _context.SaveChangesAsync();
            }
            catch (ArgumentException)
            {
                return("資料庫刪除錯誤");
            }
            return("刪除成功");

            #endregion
        }