Example #1
0
 public ActionResult Create(UploadFileModel model, HttpPostedFileBase FileUpload)
 {
     try
     {
         // TODO: Add insert logic here
         if (ModelState.IsValid && FileUpload != null)
         {
             Post post       = new Post();
             var  fileName   = Path.GetFileName(FileUpload.FileName);
             var  serverPath = Path.Combine(Server.MapPath("~/Content/images/"), fileName);
             FileUpload.SaveAs(serverPath);
             post.url   = "/Content/images/" + fileName;
             post.Title = model.title;
             int count = db.Posts.Count();
             post.Id                = count + 1;
             post.PostedDate        = DateTime.Now;
             post.ApplicationUserId = User.Identity.GetUserId();
             db.Posts.Add(post);
             db.SaveChanges();
             return(RedirectToAction("Details", "Post", new { postId = post.Id }));
         }
         return(View());
     }
     catch
     {
         return(View());
     }
 }
Example #2
0
        public JsonResult Upload(UploadFileModel form, HttpPostedFileBase fileToUpload)
        {
            try
            {
                BuildersCapitalDataProvider BuildersCapitalDataProvider = new BuildersCapitalDataProvider();
                IList <Guid> uploadedData = BuildersCapitalDataProvider.UploadDataModel(fileToUpload.InputStream);

                string           path      = Server.MapPath("~/App_Data");
                IList <Document> documents = BuildersCapitalDataProvider.VerifyDocuments(uploadedData, path);
                var result = new
                {
                    error   = 0,
                    data    = documents,
                    message = ""
                };
                return(Json(result, JsonRequestBehavior.AllowGet));
            }

            catch (Exception ex)
            {
                var result = new
                {
                    error   = 1,
                    data    = "",
                    message = ex.Message
                };
                return(Json(result, JsonRequestBehavior.AllowGet));
            }
        }
Example #3
0
        public async Task <ApiResponseModel> SaveFileAsync(UploadFileModel request, Stream fileStream)
        {
            // TODO: this validation can be better
            if (fileStream.Length == request.Size)
            {
                var messages = await _handler.ValidateFileAsync(request);

                if (messages.Any())
                {
                    return(new ApiResponseModel(HttpStatusCode.BadRequest, new FileUploadValidationResponseModel {
                        ErrorMessages = messages
                    }));
                }

                using (fileStream)
                {
                    try
                    {
                        var result = await _handler.SaveFileAsync(request, fileStream);

                        return(new ApiResponseModel(HttpStatusCode.OK, new FileUploadResponseModel {
                            Result = result
                        }));
                    }
                    catch { }
                }
            }

            return(new ApiResponseModel(HttpStatusCode.BadRequest));
        }
Example #4
0
        public IActionResult UploadByteArray(UploadFileModel file)
        {
            ResponseModel result = new ResponseModel(ResponseCode.Error, "文件上传失败");

            try
            {
                if (loginUser != null)
                {
                    file.upload_userid = loginUser.id.ToString();
                }
                //ftp文件上传
                var jsonresult = ZlsoftFtpHelper.Upload(file, HttpContext.Request.Host.Value);
                if (jsonresult.code == ResponseCode.Success)
                {
                    result.code = jsonresult.code.ToInt32();
                    result.data = jsonresult.data;
                    result.msg  = jsonresult.msg;
                }
            }
            catch (Exception ex)
            {
                result.msg = ex.Message;
                Logger.Instance.Error("上传文件发生异常", ex);
            }
            return(Json(result));
        }
Example #5
0
        public IActionResult Index(UploadFileModel uploadFileModel)
        {
            if (ModelState.IsValid)
            {
                var file = uploadFileModel.UploadFile;

                var fileName      = file.FileName;
                var fileExtension = Path.GetExtension(fileName);
                var filePath      = Path.GetFullPath(fileName);

                if (System.IO.File.Exists(fileName))
                {
                    System.IO.File.Delete(fileName);
                }

                using (var localFile = System.IO.File.OpenWrite(fileName))
                    using (var uploadedFile = file.OpenReadStream())
                    {
                        uploadedFile.CopyTo(localFile);
                    }

                if (fileExtension == ".csv")
                {
                    _uploadFilesService.ProcessCSVFile(filePath);
                }
                if (fileExtension == ".xml")
                {
                    _uploadFilesService.ProcessXMLFile(filePath);
                }
            }
            return(Ok());
        }
Example #6
0
        public IActionResult UploadFile(UploadFileModel uploadFileModel)
        {
            if (uploadFileModel.ProductId < 1)
            {
                return(NotFound());
            }
            var product = _productService.Get(uploadFileModel.ProductId);

            if (!product.IsPublic() && !CurrentUser.Can(CapabilitySystemNames.EditProduct))
            {
                return(NotFound());
            }

            if (product.ProductAttributes.All(x => x.InputFieldType != InputFieldType.FileUpload))
            {
                return(R.Fail.With("error", T("The product doesn't accept any uploads")).Result);
            }

            //guest signin if user is not signed in
            ApplicationEngine.GuestSignIn();
            var fileBytes = uploadFileModel.MediaFile.GetBytesAsync().Result;
            var upload    = new Upload()
            {
                UserId        = CurrentUser.Id,
                FileBytes     = fileBytes,
                FileType      = uploadFileModel.MediaFile.ContentType,
                FileExtension = _localFileProvider.GetExtension(uploadFileModel.MediaFile.FileName),
                Guid          = Guid.NewGuid().ToString()
            };

            _uploadService.Insert(upload);
            var downloadUrl = ApplicationEngine.RouteUrl(RouteNames.DownloadUploadFile, new { guid = upload.Guid });

            return(R.Success.With("guid", upload.Guid).With("url", downloadUrl).Result);
        }
Example #7
0
        public async Task <IActionResult> UploadFile([FromForm] UploadFileModel model, [FromServices] IBlobBucket blobBucket)
        {
            var file = model.File;

            if (file == null)
            {
                return(new ApiError(MyErrorCode.ModelInvalid, "File is null").Wrap());
            }

            if (file.Length > 1024 * 1024 * 5)            //5mb
            {
                return(new ApiError(MyErrorCode.FileTooLarge, "图片太大,不能超过5MB").Wrap());
            }


            string blobUrl;

            using (var stream = file.OpenReadStream())
            {
                blobUrl = await blobBucket.PutBlobAsync(stream, Path.GetRandomFileName());
            }

            return(Ok(new UploadFileResponse {
                Url = blobUrl
            }));
        }
Example #8
0
        /// <summary>
        /// 导入城市
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void btnImport_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();

            openFileDialog.Multiselect = false;
            openFileDialog.Filter      = "csv Files (*.csv)|*.csv;";
            if (openFileDialog.ShowDialog() != true)
            {
                return;
            }
            Stream Stream = (System.IO.Stream)openFileDialog.File.OpenRead();

            byte[] Buffer = new byte[Stream.Length];
            Stream.Read(Buffer, 0, (int)Stream.Length);
            Stream.Dispose();
            Stream.Close();

            UploadFileModel UploadFile = new UploadFileModel();

            UploadFile.FileName = openFileDialog.File.Name;
            UploadFile.File     = Buffer;
            Dictionary <string, string> empInfo = new Dictionary <string, string>();

            empInfo.Add("ownerID", SMT.SAAS.Main.CurrentContext.Common.CurrentLoginUserInfo.EmployeeID);
            client.ImportCityCSVAsync(UploadFile, empInfo, string.Empty);
            loadbar.Start();
        }
        public async Task Handle(DayAssignUploadDataUploaded message)
        {
            var model = new UploadFileModel
            {
                FileId       = Guid.Parse(message.SourceId),
                FileName     = message.Name,
                Path         = message.Path,
                ContentType  = message.ContentType,
                CreationDate = message.UploadedOn,
                UploaderId   = message.UploaderId
            };

            DayAssign dayAssign = GetDayAssignById(message.DayAssignId);

            if (dayAssign.UploadList == null)
            {
                dayAssign.UploadList = new List <UploadFileModel> {
                    model
                };
            }
            else
            {
                dayAssign.UploadList.Add(model);
            }

            await Update(message.DayAssignId.ToString(),
                         Builders <DayAssign> .Update.Set(f => f.UploadList, dayAssign.UploadList));
        }
Example #10
0
        public async Task <IActionResult> Upload(UploadFileModel model)
        {
            var    name        = model.changedname;
            var    description = model.description;
            var    files       = model.files;
            string filename;// filename in directory
            string path;

            filename = ContentDispositionHeaderValue.Parse(files.ContentDisposition).FileName.Trim('"');
            filename = this.EnsureCorrectFilename(filename);
            var uniqGuid = Guid.NewGuid().ToString();

            filename = uniqGuid + filename;
            path     = this.GetPathAndFilename(filename);
            using (FileStream output = System.IO.File.Create(path))
                await files.CopyToAsync(output);

            // DB insert

            Image = new Image();
            if (ModelState.IsValid)
            {
                Image.Name        = name;
                Image.Description = description;
                Image.Url         = "/UploadedContent/uploadedImages/" + filename;
                Image.Views       = 0;
                _db.Images.Add(Image);
                _db.SaveChanges();
            }

            return(RedirectToAction("Index"));
        }
Example #11
0
        public async Task <FileModel> SaveFileAsync(UploadFileModel fileModel)
        {
            Guid   fileId         = Guid.NewGuid();
            string serverFileName = $"{fileId}_{fileModel.FileName}";

            await ServerFileManager.SaveFileAsync(fileModel.FileStream, serverFileName);

            DateTime uploadDate = DateTime.Now;

            Context.FileModels.Add(new File
            {
                UploadDate    = uploadDate,
                UploaderId    = fileModel.UploaderId,
                ContentLength = fileModel.ContentLength,
                Id            = fileId,
                FileName      = fileModel.FileName,
                FileType      = fileModel.FileType
            });
            await Context.SaveChangesAsync();

            return(new FileModel
            {
                Id = fileId,
                UploadDate = uploadDate,
                UploaderId = fileModel.UploaderId
            });
        }
        public object upload_icon(UploadFileModel model)
        {
            string token = Request.Headers.GetValues("clientsecret").FirstOrDefault();

            if (!token.Equals(Consts.WorkFlowApIToken))
            {
                return(new { ret_code = RetCode.Error, ret_msg = "Bad request" });
            }

            string dir = Path.Combine(Dir, "icons\\");

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

            string filename = Path.Combine(dir, DateTime.Now.Ticks.ToString());

            try
            {
                byte[] bytes = Convert.FromBase64String(model.Base64String);
                using (var fs = new FileStream(filename, FileMode.Create, FileAccess.Write))
                {
                    fs.Write(bytes, 0, bytes.Length);
                    fs.Flush();
                }
            }
            catch (Exception ex)
            {
                return(new { ret_code = RetCode.Error, ret_msg = "upload failed" });
            }

            return(new { ret_code = RetCode.Success, fileName = filename });
        }
Example #13
0
        protected UploadFileModel UploadFile(IFormFile file, string folderName, int id, string strDateTime)
        {
            var model = new UploadFileModel();

            try
            {
                string currentFileExtension = Path.GetExtension(file.FileName);
                var    saveName             = id.ToString() + strDateTime + currentFileExtension;
                var    newPath = Path.Combine("images", folderName, saveName);
                var    path    = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", newPath);
                using (var stream = new FileStream(path, FileMode.Create))
                {
                    file.CopyTo(stream);
                }

                model.IsUploadSuccess = true;
                model.ErrorMessage    = "";
                return(model);
            }
            catch (Exception ex)
            {
                model.IsUploadSuccess = false;
                model.ErrorMessage    = ex.Message;
                return(model);
            }
        }
Example #14
0
        public async Task <IActionResult> UploadFile([FromBody] UploadFileModel model)
        {
            #region Validation

            if (!ModelState.IsValid)
            {
                return(BadRequest(ErrorResponse.Create(ModelState)));
            }

            #endregion

            try
            {
                var fileData = Convert.FromBase64String(model.FileData);
                var fileId   = await _service.UploadFileAsync(model.FileName, fileData, model.ParentFolderGoogleId);

                var response = new UploadFileResponse()
                {
                    GoogleId = fileId
                };

                return(Ok(response));
            }
            catch (Exception ex)
            {
                await _log.WriteErrorAsync("GoogleDriveController", nameof(UploadFile), string.Empty, ex);

                return(StatusCode(500, ErrorResponse.Create(ex.Message)));
            }
        }
Example #15
0
        public Task Handle(UploadDataUploaded message)
        {
            var model = new UploadFileModel
            {
                FileId       = Guid.Parse(message.SourceId),
                FileName     = message.Name,
                Path         = message.Path,
                ContentType  = message.ContentType,
                CreationDate = message.UploadedOn,
                UploaderId   = message.UploaderId
            };

            JobAssign jobAssign = GetJobAssignById(message.JobAssignId);

            if (jobAssign.UploadList == null)
            {
                jobAssign.UploadList = new List <UploadFileModel> {
                    model
                };
            }
            else
            {
                jobAssign.UploadList.Add(model);
            }

            return(UpdateJobAssign(message.JobAssignId,
                                   Builders <JobAssign> .Update.Set(f => f.UploadList, jobAssign.UploadList)));
        }
Example #16
0
        public ActionResult BulkInsertAction()
        {
            dynamic content = null;

            using (StreamReader @reader = new StreamReader(Request.Form.Files[0].OpenReadStream()))
            {
                content = @reader.ReadToEnd();
                @reader.Close();
            }

            UploadFileModel data = JsonConvert.DeserializeObject <UploadFileModel>(content);

            try
            {
                using (var db = new AppDbContext())
                {
                    foreach (var element in data.devices)
                    {
                        db.Machines.Add(element);
                    }

                    db.SaveChanges();
                }
            }
            catch
            {
                return(BadRequest());
            }

            return(Ok());
        }
Example #17
0
        public static async Task <string> UploadAsync(UploadFileModel model)
        {
            //Deserializing the response recieved from web api and storing into the Tender List
            var tenderList = JsonConvert.DeserializeObject <string>(await uploadRequest.PostAsync("FileNet/Upload", model));

            return(tenderList);
        }
Example #18
0
        public async Task <IActionResult> ChangeImg(int userId, [FromForm(Name = "Photo")] IFormFile Photo)
        {
            Result <string> result       = new Result <string>();
            var             uploadResult = new UploadFileModel();
            var             strDateTime  = toNZTimezone(DateTime.UtcNow).ToString("yyMMddhhmmssfff");

            try
            {
                var user = await _ablemusicContext.User.Include(s => s.Learner)
                           .Include(s => s.Teacher)
                           .Include(s => s.Staff)
                           .Include(s => s.Role)
                           .Where(s => s.UserId == userId)
                           .FirstOrDefaultAsync();

                if (user.Role.RoleId == 1)  //teacher {
                {
                    var teacher = user.Teacher.FirstOrDefault();
                    teacher.Photo = $"images/tutor/Photos/{teacher.TeacherId + strDateTime + Path.GetExtension(Photo.FileName)}";
                    _ablemusicContext.Update(teacher);
                    await _ablemusicContext.SaveChangesAsync();

                    uploadResult = UploadFile(Photo, "tutor/Photos/", teacher.TeacherId, strDateTime);
                }
                else if (user.Role.RoleId == 4)   //learner
                {
                    var learner = user.Learner.FirstOrDefault();

                    learner.Photo = $"images/learner/Photos/{learner.LearnerId + strDateTime + Path.GetExtension(Photo.FileName)}";
                    _ablemusicContext.Update(learner);
                    await _ablemusicContext.SaveChangesAsync();

                    uploadResult = UploadFile(Photo, "learner/Photos/", learner.LearnerId, strDateTime);
                }
                else   //staff
                {
                    var staff = user.Staff.FirstOrDefault();
                    staff.Photo = $"images/staff/Photos/{staff.StaffId + strDateTime + Path.GetExtension(Photo.FileName)}";
                    _ablemusicContext.Update(staff);
                    await _ablemusicContext.SaveChangesAsync();

                    uploadResult = UploadFile(Photo, "staff/Photos/", staff.StaffId, strDateTime);
                }


                if (!uploadResult.IsUploadSuccess)
                {
                    throw new Exception(uploadResult.ErrorMessage);
                }

                return(Ok(result));
            }
            catch (Exception ex)
            {
                result.IsSuccess    = false;
                result.ErrorMessage = ex.ToString();
                return(BadRequest(result));
            }
        }
Example #19
0
 public XmlProvider(IConvertToXmlService xmlConverter, UploadFileModel model,
                    string fileName, string savePath)
 {
     this._xmlConverter = xmlConverter;
     this._model        = model;
     this._fileName     = fileName;
     this._savePath     = savePath;
 }
Example #20
0
 public long UploadedFileInsert(UploadFileModel model)
 {
     using (var dbctx = DbContext)
     {
         var id = dbctx.UploadedFileInsert(model.FileName, model.FileUrl).FirstOrDefault();
         return(Convert.ToInt64(id ?? 0));
     }
 }
Example #21
0
        public IActionResult ImportExcel([FromForm] UploadFileModel model)
        {
            using var stream = model.FormFile.OpenReadStream();
            var entries = _configurationEntriesExcelReader.Read(stream);

            // TODO: import to database
            return(Ok(entries));
        }
Example #22
0
        public IActionResult ImportCsv([FromForm] UploadFileModel model)
        {
            using var stream = model.FormFile.OpenReadStream();
            var products = _productCsvReader.Read(stream);

            // TODO: import to database
            return(Ok(products));
        }
Example #23
0
        public async Task <DocumentInfo> UploadFileAsync([FromForm] UploadFileModel model)
        {
            var allowedFormats = FileFormatHelper.DocumentMimeTypes.Concat(FileFormatHelper.ImageMimeTypes).ToArray();

            var fileContent = await ReadFormFileAsync(model.File, allowedFormats).ConfigureAwait(false);

            return(await _fileService.UploadFileAsync(fileContent, UserId, $"{_contextAccessor.HttpContext.Request.Scheme}://{_contextAccessor.HttpContext.Request.Host}").ConfigureAwait(false));
        }
Example #24
0
 private string GetUploadedFileLink(UploadFileModel model, Guid dayAssignId)
 {
     if (model != null)
     {
         var extension = Path.GetExtension(model.Path);
         return(pathHelper.GetDayAssignUploadsPath(dayAssignId, model.FileId, extension));
     }
     return(string.Empty);
 }
        public async Task <string> UploadAsync(UploadFileModel model, CancellationToken token)
        {
            var storageNode = await FastDFSClient.GetStorageNodeAsync(model.GroupName);

            token.ThrowIfCancellationRequested();
            var fileId = await storageNode.UploadFileAsync(model.FileStream, model.Extension, token);

            return(_option.FileUrlPrefix + '/' + storageNode.GroupName + '/' + fileId);
        }
        private async Task <MethodResponse> UploadFileHandler(MethodRequest request, object context)
        {
            int response = 200;

            try
            {
                string          jsonString = request.DataAsJson;
                UploadFileModel model      = JsonConvert.DeserializeObject <UploadFileModel>(jsonString);

                if (model.Cancel)
                {
                    string key = FixPath(model.BlobPath) + model.BlobFilename;

                    if (uploadTokenSources.ContainsKey(key))
                    {
                        CancellationTokenSource cts = uploadTokenSources[key];
                        cts.Cancel();
                    }
                    else
                    {
                        response = 404;
                    }
                }
                else
                {
                    if (string.IsNullOrEmpty(model.SasUri))
                    {
                        string key = FixPath(model.BlobPath) + model.BlobFilename;

                        if (uploadTokenSources.ContainsKey(key))
                        {
                            uploadTokenSources.Remove(key);
                        }

                        await remote.UploadFile(model.Path, model.Filename, model.BlobPath, model.BlobFilename, model.ContentType, model.Append);
                    }
                    else
                    {
                        if (uploadTokenSources.ContainsKey(model.SasUri))
                        {
                            uploadTokenSources.Remove(model.SasUri);
                        }

                        uploadTokenSources.Add(model.SasUri, new CancellationTokenSource());
                        await remote.UploadFile(model.Path, model.Filename, model.SasUri, model.ContentType, model.Append);
                    }
                }
            }
            catch (Exception ex)
            {
                response = 500;
                Console.WriteLine("ERROR: DirectMethods-UploadFileHandler '{0}'", ex.Message);
            }


            return(new MethodResponse(response));
        }
Example #27
0
 public BaseAttachment(UploadFileModel item)
 {
     this.Id           = item.Uid;
     this.LastUpdateAt = item.LastModified;
     this.FileName     = item.Name;
     this.FileSize     = item.Size;
     this.FileType     = item.Type;
     this.Url          = item.Url;
     this.ThumbUrl     = item.ThumbUrl;
 }
Example #28
0
        public async Task <string> Upload([FromBody] UploadFileModel model)
        {
            Integration.UploadFileModel uploadFileModel = new Integration.UploadFileModel {
                FileNameField = model.FileNameField, FileContentField = model.FileContentField, FileLengthField = model.FileLengthField, MIMETypeField = model.MIMETypeField
            };
            string fileId = await _fileNetService.UploadFile(uploadFileModel);

            uploadFileModel = null;
            return(fileId);
        }
 public BaseAttachment(UploadFileModel item)
 {
     this.Id           = item.uid;
     this.LastUpdateAt = item.lastModified;
     this.FileName     = item.name;
     this.FileSize     = item.size;
     this.FileType     = item.type;
     this.Url          = item.url;
     this.ThumbUrl     = item.thumbUrl;
 }
Example #30
0
        public ActionResult UploadFile()
        {
            UploadFileModel model = new UploadFileModel();

            //{
            //    Type = enPostType.Invoice_12_5_WithAddress
            //};
            ViewData["Msg"]  = "";
            ViewData["type"] = EnumHelper.ToList(typeof(enPostType));//GetSelectListItems().ToList();
            return(View(model));
        }
        public JsonResult FileUpload(UploadFileModel input)
        {
            try
            {
                if (ModelState.IsValid && input.File.ContentLength > 0)
                {
                    var path = Path.Combine(Server.MapPath("~/File_Drop/"), input.File.FileName);

                    if (!System.IO.File.Exists(path))
                    {
                        var transactionList = MyCsvHelper.ReadFile(input.File.InputStream);
                        var result = TransactionHelper.ValidateFile(ref transactionList);

                        //Inserting the record to DB using Bulk Insert
                        _db.Add(transactionList);

                        ViewBag.FileUploadStatus = "Success";

                        //Saving the file after the Insertion is successful.
                        input.File.SaveAs(path);

                        return Json(new
                        {
                            RecordsUploaded = result.Item1,
                            RecordsSkipped = result.Item2
                        }, JsonRequestBehavior.AllowGet);
                    }

                    else
                    {
                        Response.StatusCode = (int)HttpStatusCode.Conflict;
                        ViewBag.FileUploadStatus = "Failed";
                        return Json("This File is already uploaded. Please select a new file", JsonRequestBehavior.AllowGet);
                    }

                }

                else
                {
                    var allErrors = ModelState.Values.SelectMany(v => v.Errors);
                    Response.StatusCode = (int)HttpStatusCode.BadRequest;
                    return Json(allErrors);
                }
            }
            catch (Exception)
            {
                Response.StatusCode = (int)HttpStatusCode.BadRequest;
                ViewBag.FileUploadStatus = "Failed";
                return Json("Please check the file and try again");
            }
        }
Example #32
0
        public void Add(UploadFileModel model, string user, string path)
        {
            PWMM.Models.DB.Image image = new PWMM.Models.DB.Image();
            image.ID_IMAGE = 35; // dre.Image.OrderByDescending(u => u.ID_IMAGE).Take(1).SingleOrDefault().ID_IMAGE + 1;
            image.ID_USER = 20; //(from o in dre.Profil where o.LOGIN == user.ToString() select o).First(1)
            image.IMAGE1 = path.ToString();
            image.SOURCE = model.Source;
            image.TITLE = model.Title;
            image.TITLE2 = model.Title2;
            image.DATE = DateTime.Now;

            dre.AddToImage(image);
            dre.SaveChanges();
        }
Example #33
0
        public void SaveFile(UploadFileModel UploadFile, out string strFilePath)
        {
            // Store File to File System
            string strVirtualPath = ConfigurationManager.AppSettings["FileUploadLocation"].ToString();
            string strPath = HttpContext.Current.Server.MapPath(strVirtualPath) + UploadFile.FileName;
            if (Directory.Exists(HttpContext.Current.Server.MapPath(strVirtualPath)) == false)
            {
                Directory.CreateDirectory(HttpContext.Current.Server.MapPath(strVirtualPath));
            }
            FileStream FileStream = new FileStream(strPath, FileMode.Create);
            FileStream.Write(UploadFile.File, 0, UploadFile.File.Length);

            FileStream.Close();
            FileStream.Dispose();

            strFilePath = strVirtualPath + UploadFile.FileName;
        }
Example #34
0
        public void SaveFileReturnFilePath(UploadFileModel UploadFile, out string strFilePath)
        {
            // Store File to File System
            string strNewFileName = string.Empty;
            string strVirtualPath = ConfigurationManager.AppSettings["FileUploadLocation"].ToString();
            if (!string.IsNullOrWhiteSpace(UploadFile.FileName))
            {
                strNewFileName = DateTime.Now.ToString("yyMMddhhmmss") + DateTime.Now.Millisecond.ToString() + UploadFile.FileName.Substring(UploadFile.FileName.LastIndexOf("."));
            }

            string strPath = HttpContext.Current.Server.MapPath(strVirtualPath) + strNewFileName;
            if (Directory.Exists(HttpContext.Current.Server.MapPath(strVirtualPath)) == false)
            {
                Directory.CreateDirectory(HttpContext.Current.Server.MapPath(strVirtualPath));
            }
            FileStream FileStream = new FileStream(strPath, FileMode.Create);
            FileStream.Write(UploadFile.File, 0, UploadFile.File.Length);

            FileStream.Close();
            FileStream.Dispose();

            strFilePath = strVirtualPath + strNewFileName;
        }
Example #35
0
 public UploadFileModel UploadFile(HttpPostedFileBase uploadFile,string appSettingName,params object[] args)
 {
     string rootPath=HttpContext.Current.Server.MapPath("~/");
     string uploadFilePath=Path.Combine(rootPath,string.Format(this.UploadPathKeys[appSettingName].Value,args));
     string directoryName=Path.GetDirectoryName(uploadFilePath);
     UploadFileModel uploadFileModel=null;
     if(Directory.Exists(directoryName)==false) {
         Directory.CreateDirectory(directoryName);
     }
     if(File.Exists(uploadFilePath)) {
         File.Delete(uploadFilePath);
     }
     uploadFile.SaveAs(uploadFilePath);
     FileInfo fileInfo=new FileInfo(uploadFilePath);
     uploadFileModel=new UploadFileModel {
         FileName=fileInfo.Name,
         FilePath=directoryName.Replace(rootPath,""),
         Size=fileInfo.Length
     };
     return uploadFileModel;
 }
Example #36
0
 public bool ImportCityCSV(UploadFileModel uploadFile, Dictionary<string, string> empInfoDic, ref string strMsg)
 {
     string strPath = string.Empty;
     SaveFile(uploadFile, out strPath);//获取文件路径
     string strPhysicalPath = System.Web.HttpContext.Current.Server.MapPath(strPath);//到时测试strPath为空是是否报错
     using (SysDictionaryBLL bll = new SysDictionaryBLL())
     {
         return bll.ImportCityCSV(strPhysicalPath, empInfoDic, ref strMsg);
     }
 }
Example #37
0
 public UploadFileModel UploadTempFile(HttpPostedFileBase uploadFile)
 {
     UploadFileModel uploadFileModel=null;
     if(uploadFile!=null) {
         string fileName=uploadFile.FileName;
         if(string.IsNullOrEmpty(fileName)==false) {
             string rootPath=HttpContext.Current.Server.MapPath("~/");
             string tempFileName=Path.Combine(rootPath,string.Format(this.UploadPathKeys["TempUploadPath"].Value,fileName));
             string directoryName=Path.GetDirectoryName(tempFileName);
             if(Directory.Exists(directoryName)==false) {
                 Directory.CreateDirectory(directoryName);
             }
             uploadFile.SaveAs(tempFileName);
             FileInfo fileInfo=new FileInfo(tempFileName);
             uploadFileModel=new UploadFileModel {
                 FileName=fileInfo.Name,
                 FilePath=directoryName,
                 Size=fileInfo.Length
             };
         }
     }
     return uploadFileModel;
 }
Example #38
0
        /// <summary>
        ///  读取社保卡的Excel文件,并导入数据库,返回导入后的结果
        /// </summary>
        private UploadFileModel ImportClockInRd()
        {
            string strMsg = string.Empty;
            Stream stream = null;
            try
            {
                if (openFileDialog == null)
                    return null;

                if (openFileDialog.File == null)
                    return null;

                RefreshUI(RefreshedTypes.ProgressBar);

                stream = (System.IO.Stream)openFileDialog.File.OpenRead();

                byte[] Buffer = new byte[stream.Length];
                stream.Read(Buffer, 0, (int)stream.Length);

                stream.Dispose();
                stream.Close();

                UploadFileModel UploadFile = new UploadFileModel();
                UploadFile.FileName = openFileDialog.File.Name;
                UploadFile.File = Buffer;

                strMsg = string.Empty;
                return UploadFile;
                //clientAtt.ImportClockInRdListFromExcelAsync(UploadFile, dtStart, dtEnd, strMsg);
            }
            catch (Exception )
            {
                //Utility.ShowCustomMessage(MessageTypes.Error, Utility.GetResourceStr("ERROR"), Utility.GetResourceStr(ex.Message.ToString()));

                ComfirmWindow.ConfirmationBoxs(Utility.GetResourceStr("ERROR"), Utility.GetResourceStr("ERRORINFO"),
                               Utility.GetResourceStr("CONFIRM"), MessageIcon.Error);
                return null;
            }
            finally
            {
                stream.Dispose();
                stream.Close();
            }
        }
Example #39
0
        /// <summary>
        /// 导入城市
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void btnImport_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Multiselect = false;
            openFileDialog.Filter = "csv Files (*.csv)|*.csv;";
            if (openFileDialog.ShowDialog() != true)
            {
                return;
            }
            Stream Stream = (System.IO.Stream)openFileDialog.File.OpenRead();
            byte[] Buffer = new byte[Stream.Length];
            Stream.Read(Buffer, 0, (int)Stream.Length);
            Stream.Dispose();
            Stream.Close();

            UploadFileModel UploadFile = new UploadFileModel();
            UploadFile.FileName = openFileDialog.File.Name;
            UploadFile.File = Buffer;
            Dictionary<string, string> empInfo = new Dictionary<string, string>();
            empInfo.Add("ownerID", SMT.SAAS.Main.CurrentContext.Common.CurrentLoginUserInfo.EmployeeID);
            client.ImportCityCSVAsync(UploadFile, empInfo, string.Empty);
             loadbar.Start();
        }
Example #40
0
        /// <summary>
        ///  读取部门岗位的Excel文件,并导入数据库,返回导入后的结果
        /// </summary>
        private void ImportOrgInfo()
        {
            string strMsg = string.Empty;
            try
            {
                RefreshUI(RefreshedTypes.ShowProgressBar);
                if (acbCompanyName.SelectedItem==null)
                {
                    tbFileName.Text = string.Empty;//不显示文件
                  ComfirmWindow.ConfirmationBoxs(Utility.GetResourceStr("CAUTION"),Utility.GetResourceStr("SELECTCOMPANY"),
                      Utility.GetResourceStr("CONFIRM"), MessageIcon.Exclamation);
                  RefreshUI(RefreshedTypes.HideProgressBar);
                  return;
                }
                if (OpenFileDialog == null || OpenFileDialog.File == null)
                {
                    tbFileName.Text = string.Empty;//不显示文件
                    return;
                }
                Stream Stream = (System.IO.Stream)OpenFileDialog.File.OpenRead();

                byte[] Buffer = new byte[Stream.Length];
                Stream.Read(Buffer, 0, (int)Stream.Length);

                Stream.Dispose();
                Stream.Close();
                UploadFileModel UploadFile = new UploadFileModel();
                UploadFile.FileName = OpenFileDialog.File.Name;
                UploadFile.File = Buffer;
                string companyID = (acbCompanyName.SelectedItem as T_HR_COMPANY).COMPANYID;
                Dictionary<string, string> empInfo = new Dictionary<string, string>();
                empInfo.Add("ownerID", SMT.SAAS.Main.CurrentContext.Common.CurrentLoginUserInfo.EmployeeID);
                empInfo.Add("ownerPostID", SMT.SAAS.Main.CurrentContext.Common.CurrentLoginUserInfo.UserPosts[0].PostID);
                empInfo.Add("ownerDepartmentID", SMT.SAAS.Main.CurrentContext.Common.CurrentLoginUserInfo.UserPosts[0].DepartmentID);
                empInfo.Add("ownerCompanyID", SMT.SAAS.Main.CurrentContext.Common.CurrentLoginUserInfo.UserPosts[0].CompanyID);
                client.ImportOrgInfoAsync(UploadFile, companyID, empInfo);
            }
            catch (Exception ex)
            {
                ComfirmWindow.ConfirmationBoxs(Utility.GetResourceStr("ERROR"), ex.ToString(), Utility.GetResourceStr("CONFIRM"), MessageIcon.Error);
                RefreshUI(RefreshedTypes.HideProgressBar);
            }
        }
Example #41
0
        public List<T_HR_PENSIONDETAIL> ImportClockInRdListFromExcelForShow(UploadFileModel UploadFile, Dictionary<string, string> paras, ref string strMsg)
        {
            List<T_HR_PENSIONDETAIL> ListResult = new List<T_HR_PENSIONDETAIL>();
            try
            {
                Tracer.Debug("import start" + paras.Count.ToString());
                string strPath = string.Empty;
                SaveFileReturnFilePath(UploadFile, out strPath);
                string strPhysicalPath = HttpContext.Current.Server.MapPath(strPath);

                using (PensionDetailBLL bll = new PensionDetailBLL())
                {
                    ListResult = bll.ImportPensionByImportExcelForShow(strPhysicalPath, paras, ref strMsg);
                }
                Tracer.Debug("import sucess");
            }
            catch (Exception ex)
            {
                Tracer.Debug("ImportClockInRdListFromExcelWS:" + ex.Message);
            }
            return ListResult;
        }
Example #42
0
 public string ImportEmployeeMonthlySalary(UploadFileModel UploadFile, GenerateUserInfo GenerateUser, string year, string month, ref string owerCompayId, ref string UImsg)
 {
     string strPath = string.Empty;
     SaveFile(UploadFile, out strPath);
     string strPhysicalPath = HttpContext.Current.Server.MapPath(strPath);
     using (EmployeeSalaryImportBLL bll = new EmployeeSalaryImportBLL())
     {
         return bll.ImportEmployeeMonthlySalary(GenerateUser, strPhysicalPath, year, month, owerCompayId, ref UImsg);
     }
 }
Example #43
0
 public List<V_ORGANIZATIONINFO> ImportOrgInfo(UploadFileModel uploadFile, string companyID, Dictionary<string, string> empInfoDic)
 {
     using (DepartmentBLL bll = new DepartmentBLL())
     {
         string strPath = SaveFile(uploadFile);//获取文件路径
         string strPhysicalPath = HttpContext.Current.Server.MapPath(strPath);//到时测试strPath为空是是否报错
         return bll.ImportOrgInfo(strPhysicalPath, companyID, empInfoDic);
     }
 }
Example #44
0
 public List<T_HR_EMPLOYEESALARYRECORD> ImportExcel(UploadFileModel UploadFile, out int failcount, out int successcount, string year, string month, string paySign)
 {
     string strPath = string.Empty;    //, int pageIndex, int pageSize, ref int pageCount, ref string strMsg
     SaveFile(UploadFile, out strPath);
     string strPhysicalPath = HttpContext.Current.Server.MapPath(strPath);
     using (PaymentBLL bll = new PaymentBLL())
     {
         return bll.ReadExcel(strPhysicalPath, out failcount, out successcount, year, month, paySign);
     }
 }
Example #45
0
        public List<T_HR_EMPLOYEEADDSUM> ImportEmployeeAddSumFromExcelForShow(UploadFileModel UploadFile, Dictionary<string, string> paras, ref string strMsg, bool IsPreview)
        {
            List<T_HR_EMPLOYEEADDSUM> ListResult = new List<T_HR_EMPLOYEEADDSUM>();
            try
            {
                Tracer.Debug("import start" + paras.Count.ToString());
                string strPath = string.Empty;
                SaveFile(UploadFile, out strPath);
                string strPhysicalPath = HttpContext.Current.Server.MapPath(strPath);

                using (EmployeeAddSumBLL bll = new EmployeeAddSumBLL())
                {
                    ListResult = bll.ImportEmployeeAddSumFromExcelForShow(strPhysicalPath, paras, ref strMsg,IsPreview);
                }
                Tracer.Debug("import sucess");
            }
            catch (Exception ex)
            {
                Tracer.Debug("ImportClockInRdListFromExcelWS:" + ex.Message);
            }
            return ListResult;
        }
Example #46
0
        public void ImportAttendMonthlyBalanceFromCSV(UploadFileModel UploadFile, string strCreateUserID, string strUnitType, string strUnitObjectId, decimal dBalanceYear, decimal dBalanceMonth, ref string strMsg)
        {
            string strPath = string.Empty;
            SaveFileReturnFilePath(UploadFile, out strPath);
            string strPhysicalPath = HttpContext.Current.Server.MapPath(strPath);

            using (AttendMonthlyBalanceBLL bllAttendMonthlyBalance = new AttendMonthlyBalanceBLL())
            {
                bllAttendMonthlyBalance.ImportMonthlyBalance(strCreateUserID, strPhysicalPath, strUnitType, strUnitObjectId, dBalanceYear, dBalanceMonth, ref strMsg);
            }
        }
Example #47
0
 public List<V_EmployeeEntryInfo> ImportEmployeeEntry(UploadFileModel uploadFile, string companyID, Dictionary<string, string> empInfoDic)
 {
     using (EmployeeEntryBLL bll = new EmployeeEntryBLL())
     {
         string strPath = string.Empty;
         SaveFileReturnFilePath(uploadFile, out strPath);//获取文件路径
         string strPhysicalPath = HttpContext.Current.Server.MapPath(strPath);//到时测试strPath为空是是否报错
         return bll.ImportEmployeeEntry(strPhysicalPath, companyID, empInfoDic);
     }
 }
Example #48
0
        public void ImportClockInRdListFromFileAndLoginData(UploadFileModel UploadFile, string strFileType, string strUnitType, string strUnitObjectId, DateTime dtStart, DateTime dtEnd, ref string strMsg)
        {
            string strPath = string.Empty;
            SaveFileReturnFilePath(UploadFile, out strPath);
            string strPhysicalPath = HttpContext.Current.Server.MapPath(strPath);

            using (ClockInRecordBLL bllClockInRecord = new ClockInRecordBLL())
            {
                bllClockInRecord.ImportClockInRdListByImportFileAndLoginData(strPhysicalPath, strFileType, strUnitType, strUnitObjectId, dtStart, dtEnd, ref strMsg);
            }
        }
Example #49
0
        public void ImportClockInRdListFromExcel(UploadFileModel UploadFile, Dictionary<string, string> paras, ref string strMsg)
        {
            try
            {
                Tracer.Debug("import start" + paras.Count.ToString());
                string strPath = string.Empty;
                SaveFileReturnFilePath(UploadFile, out strPath);
                string strPhysicalPath = HttpContext.Current.Server.MapPath(strPath);

                using (PensionDetailBLL bll = new PensionDetailBLL())
                {
                    bll.ImportPensionByImportExcel(strPhysicalPath, paras, ref strMsg);
                }
                Tracer.Debug("import sucess");
            }
            catch (Exception ex)
            {
                Tracer.Debug("ImportClockInRdListFromExcelWS:" + ex.Message);
            }
        }
Example #50
0
        public void ImportClockInRdListFromFile(UploadFileModel UploadFile, string strFileType, string strUnitType, string strUnitObjectId, DateTime dtStart, DateTime dtEnd, ref string strMsg)
        {
            string strPath = string.Empty;
            SaveFileReturnFilePath(UploadFile, out strPath);
            string strPhysicalPath = HttpContext.Current.Server.MapPath(strPath);

            using (ClockInRecordBLL bllClockInRecord = new ClockInRecordBLL())
            {
                if (strFileType.ToLower() == "csv")
                {
                    bllClockInRecord.ImportClockInRdListByImportCSV(strPhysicalPath, strUnitType, strUnitObjectId, dtStart, dtEnd, ref strMsg);
                }
                else if (strFileType.ToLower() == "xls")
                {
                    bllClockInRecord.ImportClockInRdListByImportExcel(strPhysicalPath, strUnitType, strUnitObjectId, dtStart, dtEnd, ref strMsg);
                }
            }
        }
Example #51
0
        public string SaveFile(UploadFileModel uploadFile)
        {
            try
            {
                // Store File to File System
                string strVirtualPath = ConfigurationManager.AppSettings["FileUploadLocation"].ToString();
                string strPath = HttpContext.Current.Server.MapPath(strVirtualPath) + uploadFile.FileName;
                if (Directory.Exists(HttpContext.Current.Server.MapPath(strVirtualPath)) == false)
                {
                    Directory.CreateDirectory(HttpContext.Current.Server.MapPath(strVirtualPath));
                }
                FileStream FileStream = new FileStream(strPath, FileMode.Create);
                FileStream.Write(uploadFile.File, 0, uploadFile.File.Length);

                FileStream.Close();
                FileStream.Dispose();

                string strFilePath = strVirtualPath + uploadFile.FileName;
                return strFilePath;
            }
            catch (Exception ex)
            {
                SMT.Foundation.Log.Tracer.Debug("获取文件路径错误::" + ex.ToString());
                return string.Empty;
            }
        }
Example #52
0
 public List<T_HR_ATTENDMONTHLYBALANCE> ImportAttendMonthlyBalanceForShow(UploadFileModel UploadFile)
 {
     string strPath = string.Empty;
     SaveFileReturnFilePath(UploadFile, out strPath);
     string strPhysicalPath = HttpContext.Current.Server.MapPath(strPath);
     using (AttendMonthlyBalanceBLL bllAttendMonthlyBalance = new AttendMonthlyBalanceBLL())
     {
         return bllAttendMonthlyBalance.ImportMonthlyBalanceForShow(strPhysicalPath);
     }
 }