コード例 #1
0
ファイル: ProjectController.cs プロジェクト: diliger/AdCrm
        public ActionResult Files(int ID)
        {
            string settingsName = "Project.Files";

            User    user    = HttpContext.CurrentUser();
            int     userID  = user.ID;
            Project project = db.Projects.FirstOrDefault(val => val.ID == ID && !val.Deleted);

            if (!Available(project))
            {
                ViewBag.Error = "Forbidden";
                return(View("Error"));
            }

            DateTime         date   = DateTime.Now;
            UploadFileHelper helper = new UploadFileHelper(db);
            Folder           folder = helper.GetFolder(project, true);

            object data = new
            {
                Folder   = folder.ToJson(),
                Projects = new[] { project }.Select(val => val.ToJson("Details")).ToList(),
                //Users = users.Select(val => val.ToJson()).ToList(),
                ProjectProperties = project.GetJsonProperties("Details"),
                //Statbooks = db.Statbooks.Where(val => val.TypeID == (int)StatbookTypesEnum.TaskStatuses).ToList().Select(val => val.ToJson()).ToList(),
                Settings = db.UserSettings.Where(val => val.UserID == userID && val.Name.StartsWith(settingsName)).ToList().Select(val => val.ToJson()).ToList()
            };

            ViewBag.Project = project;
            ViewBag.Data    = serializer.Serialize(data);
            ViewBag.Page    = settingsName;
            return(View());
        }
コード例 #2
0
        public bool RemoveFile(string realName, long id)
        {
            var attachmentService = EngineContext.Current.Resolve <IAttachmentService>();
            var response          = attachmentService.DeleteAttackmentById(id);
            var result            = new HrmResultModel <AttachmentModel>();

            if (response != null)
            {
                result = JsonConvert.DeserializeObject <HrmResultModel <AttachmentModel> >(response);
                if (!CheckPermission(result))
                {
                    //return to Access Denied
                }
                else
                {
                    UploadFileHelper.RemoveFileUpload(realName);
                    if (result.Results.Count > 0)
                    {
                        result.Success = false;
                    }
                    else
                    {
                        result.Success = true;
                    }
                }
            }
            return(result.Success);
        }
コード例 #3
0
        public IHttpActionResult Post(string Type)
        {
            if (Type == null)
            {
                return(BadRequest("请指定照片种类"));
            }
            HttpFileCollection files = HttpContext.Current.Request.Files;

            if (files.Count == 0)
            {
                return(BadRequest("请上传文件"));
            }
            Models.Type type = db.Types.First(s => s.Name == Type);
            if (type == null)
            {
                return(BadRequest("不存在此照片种类"));
            }
            HttpPostedFile file      = files[0];
            string         directory = null;
            string         extension = new FileInfo(file.FileName).Extension;
            string         fileName  = Type + DateTime.Now.ToString("yyyyMMddHHmmssfff");
            string         result    = null;

            directory = @"\Photos\" + type.Name;
            result    = UploadFileHelper.UploadImage(file, directory, fileName, extension);
            if (!string.IsNullOrEmpty(result))
            {
                return(BadRequest(result));
            }
            string url = (directory + "/" + fileName + extension).Replace("\\", "/");

            return(Ok(url));
        }
コード例 #4
0
        public int SaveFile(IEnumerable <HttpPostedFileBase> attachment, string dataType, long recordId)
        {
            var fileUpload = UploadFileHelper.SaveFile(attachment);

            if (fileUpload != null && fileUpload.Count > 0)
            {
                foreach (var file in fileUpload)
                {
                    var attachmentModel = new AttachmentModel()
                    {
                        FileName        = file.Realname,
                        FileSize        = file.Size,
                        DisplayFileName = file.Name,
                        RecordId        = recordId,
                        DataType        = dataType,
                        FileExtension   = file.Extension
                    };
                    var attachmentEntity  = MapperHelper.Map <AttachmentModel, AttachmentEntity>(attachmentModel);
                    var attachmentService = EngineContext.Current.Resolve <IAttachmentService>();
                    attachmentService.SaveAttachment(attachmentEntity);
                }
            }
            var result = fileUpload.Count;

            return(result);
        }
コード例 #5
0
ファイル: Ged.cs プロジェクト: clasie/T-P
        /// <summary>
        /// UploadFile according to the the doc type
        /// </summary>
        /// <param name="barcode"></param>
        /// <param name="entirePathFileToUpload"></param>
        /// <param name="enumDocType"></param>
        /// <returns></returns>
        public GEDJsonClassRequestResponse UploadFile(
            string barcode,
            string entirePathFileToUpload,
            GedService.DocTypesEnum enumDocType,
            bool doubleCheckTheUpload = false
            )
        {
            //File Validation before going further
            FileValidationHelper.ValidateFile(entirePathFileToUpload);

            //GED Web call preparation
            string    requestURL = $"{GEDUrl}{GedConstants.WebSeparator}{GedConstants.ServiceUpload}";
            string    fileName   = entirePathFileToUpload;
            WebClient wc         = new WebClient();

            byte[] bytes = wc.DownloadData(fileName); //in case the file is on another server.
            wc.Dispose();

            string userAgent          = GedConstants.WebUserAgent;
            string returnResponseText = string.Empty;

            int loopsMax = GedConstants.LoopGetTokenMinConterValue;

            while (loopsMax++ < GedConstants.LoopGetTokenMaxConterValue)
            {
                try
                {
                    //Prepare parameters
                    Dictionary <string, object> postParameters = new Dictionary <string, object>();
                    postParameters.Add(GedConstants.ParameterFile, new UploadFileHelper.FileParameter(bytes, Path.GetFileName(fileName), HttpParamContentType));
                    postParameters.Add(GedConstants.ParameterToken, Token);
                    postParameters.Add(GedConstants.ParameterDocType, enumDocType.ToString());
                    postParameters.Add(GedConstants.ParameterBarCode, barcode);
                    postParameters.Add(GedConstants.ParameterProvider, string.Empty);
                    //Prepare call the service
                    HttpWebResponse webResponse =
                        UploadFileHelper.MultipartFormPost(
                            requestURL,
                            userAgent,
                            postParameters,
                            GedConstants.HeaderCacheParam,
                            GedConstants.HeaderCacheValue
                            );
                    //Call the service
                    StreamReader responseReader = new StreamReader(webResponse.GetResponseStream());
                    returnResponseText = responseReader.ReadToEnd();
                    //Analyse the response
                    return(ExceptionCallerHelper.UploadFileTestExecute(returnResponseText, bytes.Length));
                }
                //The token has expired, we try again just once
                catch (GEDTokenException gedTokenException)
                {
                    Token = GetConnectionToken().Token;
                }
            }
            return(new GEDJsonClassRequestResponse()
            {
                error = $"{GedConstants.UnknownDEGDllError}, {this.GetType().Name}.{System.Reflection.MethodBase.GetCurrentMethod().Name}"
            });
        }
コード例 #6
0
        public ActionResult UploadToFolder(string ID, int?FolderID, int FileID = -1)
        {
            ViewBag.ID     = ID;
            ViewBag.FileID = FileID;
            User user = HttpContext.CurrentUser();

            if (Request.Files.Count < 1)
            {
                return(View());
            }

            bool             watermark = ID.ToLower() != "photoid";
            int              code;
            string           message;
            UploadFileHelper helper = new UploadFileHelper(this.db as BuildingEntities);

            Models.File file = helper.UploadFiles(FileID, FolderID, out code, out message, watermark);

            var data = new { Code = code, Message = message, File = file != null?file.ToJson() : null, ID = ID };

            if (ID.IsNotNullOrEmpty() && ID.ToLower().Trim().StartsWith("json"))
            {
                return(this.Json(data));
            }

            ViewBag.Data = serializer.Serialize(data);
            //ViewBag.Data = Newtonsoft.Json.JsonConvert.SerializeObject(data, new Newtonsoft.Json.JsonSerializerSettings() { DateFormatHandling = Newtonsoft.Json.DateFormatHandling.MicrosoftDateFormat });

            return(View());
        }
コード例 #7
0
        public virtual ActionResult UploadPhoto(HttpPostedFileBase fileData)
        {
            var fileInfo = UploadFileHelper.Upload(fileData, "Photos/");

            return(new JsonResult {
                Data = fileInfo
            });
        }
コード例 #8
0
        /// <summary>
        /// 上传UPC文件
        /// </summary>
        /// <param name="guid">guid</param>
        /// <returns>返回文件名</returns>
        /// <author>范永坚 2017/11/29</author>
        public string UploadFile(string guid)
        {
            //HttpPostedFile 和 HttpPostedFileBase不存在关系,但是可以通过包装类来转换
            HttpPostedFileBase file   = new HttpPostedFileWrapper(Request.Files["stuExcel"]);
            UploadFileHelper   upload = new UploadFileHelper(file);

            return(upload.Upload(file.FileName + guid, "upload"));
        }
コード例 #9
0
        public void TestUploadFile()
        {
            NameValueCollection data = new NameValueCollection();

            data.Add("name", "木子屋");
            data.Add("fileName", "a");
            data.Add("url", "http://www.mzwu.com/");
            Console.WriteLine(UploadFileHelper.HttpUploadFile("http://*****:*****@"E:\Index.htm", @"E:\test.rar" }, data));
        }
コード例 #10
0
        public async Task <ResponseModel> Handle(MultipleFileUploadCommand request, CancellationToken cancellationToken)
        {
            var errorModel = new FormFileErrorModel();

            if (!MultipartRequestHelper.IsMultipartContentType(_accessor.HttpContext.Request.ContentType))
            {
                errorModel.Errors.Add("File",
                                      $"The request couldn't be processed (Error 1).");

                return(ResponseProvider.Ok(errorModel));
            }
            var boundary = MultipartRequestHelper.GetBoundary(
                MediaTypeHeaderValue.Parse(_accessor.HttpContext.Request.ContentType),
                _defaultFormOptions.MultipartBoundaryLengthLimit);
            var reader  = new MultipartReader(boundary, _accessor.HttpContext.Request.Body);
            var section = await reader.ReadNextSectionAsync(cancellationToken);

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

                if (hasContentDispositionHeader)
                {
                    if (!MultipartRequestHelper
                        .HasFileContentDisposition(contentDisposition))
                    {
                        errorModel.Errors.Add("File", $"The request couldn't be processed (Error 2).");

                        return(ResponseProvider.Ok(errorModel));
                    }
                    else
                    {
                        var streamedFileContent = await FileHelpers.ProcessStreamedFile(
                            section, contentDisposition, errorModel,
                            _permittedExtensions, _streamFileLimitSize, ValidateExtension.Encrypt);

                        if (errorModel.Errors.Any())
                        {
                            return(ResponseProvider.Ok(errorModel));
                        }
                        var fileName = FileHelpers.GetFileName(section.ContentDisposition);

                        var fileNameWithEncryptExtension = UploadFileHelper.GetFileNameWithEncryptExtension(fileName, request.EncryptAlg);
                        var uploadFileAbsolutePath       = UploadFileHelper.GetUploadAbsolutePath(_contentRootPath, fileNameWithEncryptExtension, request.Archive);

                        await UploadFile(streamedFileContent, uploadFileAbsolutePath, request.EncryptAlg);
                    }
                }

                section = await reader.ReadNextSectionAsync(cancellationToken);
            }

            return(ResponseProvider.Ok("Upload file successfully"));
        }
コード例 #11
0
        public ActionResult SaveUserImag()
        {
            BizResultInfo result = UploadFileHelper.UploadFileToUserImg(Request);

            if (result.IsSuccess)
            {
                result.SuccessMessage = "上传成功!";
            }
            return(Json(result));
        }
コード例 #12
0
ファイル: SearchAutomation.cs プロジェクト: ADeltaX/MSEdgeBot
        private static async Task UploadAndSendMessage(EdgeFile fileElement, string captionHtml)
        {
            string file = Path.Combine(DownloadFolder, fileElement.FileName);

            if (!File.Exists(file))
            {
                SharedDBcmd.TraceError($"Internal error: File is not downloaded => " + file);
                Console.WriteLine("File is not downloaded => " + file);
                return;
            }

            await UploadFileHelper.UploadFileAsync(file, captionHtml);
        }
コード例 #13
0
        public ActionResult UploadWebBookmarkFile()
        {
            var result = UploadFileHelper.UploadFileToUserImportFile(Request);

            if (result.IsSuccess)
            {
                BizUserWebBookmarkImportLog importLog = result.Target as BizUserWebBookmarkImportLog;
                importLog.UserInfoID = UILoginHelper.GetUIDFromHttpContext(HttpContext);
                importLog.Save();
                result.ResultID = importLog.UserWebBookmarkImportLogID.ConvertToCiphertext();
            }

            return(Json(result));
        }
コード例 #14
0
        /// <summary>物理复制全部附件信息到实体类</summary>
        /// <param name="param"><see cref="IAttachmentFileInfo" />实例详细信息</param>
        /// <param name="entityId">实体标识</param>
        /// <param name="entityClassName">实体类名称</param>
        /// <returns>新的<see cref="IAttachmentFileInfo" />实例详细信息</returns>
        public IAttachmentFileInfo Copy(IAttachmentFileInfo param, string entityClassName, string entityId)
        {
            IAttachmentParentObject parent = new AttachmentParentObject();

            parent.EntityId                  = entityId;
            parent.EntityClassName           = entityClassName;
            parent.AttachmentEntityClassName = KernelContext.ParseObjectType(typeof(AttachmentFileInfo));
            parent.AttachmentFolder          = UploadPathHelper.GetAttachmentFolder(param.VirtualPath, param.FolderRule);

            IAttachmentFileInfo attachment = UploadFileHelper.CreateAttachmentFile(parent, param.AttachmentName, param.FileType, param.FileSize, param.FileData);

            attachment.Save();

            return(attachment);
        }
コード例 #15
0
        public async Task <ResponseModel> Handle(BufferedMultipleFileUploadPhysicalCommand request, CancellationToken cancellationToken)
        {
            var errorModel = new FormFileErrorModel();

            foreach (var formFile in request.Files)
            {
                var formFileContent =
                    await FileHelpers
                    .ProcessFormFile <BufferedMultipleFileUploadPhysical>(
                        formFile, errorModel, _permittedExtensions,
                        _defaultFileSizeLimit);

                if (errorModel.Errors.Any())
                {
                    return(ResponseProvider.Ok(errorModel));
                }

                // For the file name of the uploaded file stored
                // server-side, use Path.GetRandomFileName to generate a safe
                // random file name.

                var filePath = UploadFileHelper.GetUploadAbsolutePath(_contentRootPath, formFile.FileName, request.Archive);
                //var trustedFileNameForFileStorage = Path.GetRandomFileName();
                //var filePath = Path.Combine(
                //    _targetFilePath, trustedFileNameForFileStorage);

                // **WARNING!**
                // In the following example, the file is saved without
                // scanning the file's contents. In most production
                // scenarios, an anti-virus/anti-malware scanner API
                // is used on the file before making the file available
                // for download or for use by other systems.
                // For more information, see the topic that accompanies
                // this sample.

                using (var fileStream = File.Create(filePath))
                {
                    await fileStream.WriteAsync(formFileContent, cancellationToken);

                    // To work directly with the FormFiles, use the following
                    // instead:
                    //await formFile.CopyToAsync(fileStream);
                }
            }
            return(ResponseProvider.Ok("Upload file successful"));
        }
コード例 #16
0
        public ActionResult UploadProductImg(int pId, int index)
        {
            if (Request.Files.Count == 0)
            {
                return(Json(new { result_code = 0, result_msg = "文件格式不正确或者文件过大!" }));
            }
            HttpPostedFileBase uploadFile = Request.Files[0];//只示范上传一个文件

            if (uploadFile == null || uploadFile.ContentLength <= 0)
            {
                return(Json(new { result_code = 0, result_msg = "无上传文件" }));
            }
            // 如果没有上传文件
            //if (filedata == null || string.IsNullOrEmpty(filedata.FileName) || filedata.ContentLength == 0)
            //{
            //    return Json(new { result_code = 0, result_msg = "无上传文件" });
            //}
            var                  uploadFileExtension = Path.GetExtension(uploadFile.FileName).ToLower();
            string               imgName             = pId + "_" + index;
            OssUploadFile        img1      = new OssUploadFile("Getinge/ProductInfo", imgName, uploadFileExtension);
            UploadFileHelper     imgHelper = new UploadFileHelper(img1, uploadFile.InputStream);
            string               imgUrl    = imgHelper.UploadFile();
            Getinge_Product_Info model     = (from a in db.Getinge_Product_Info
                                              where a.product_id == pId && a.info_img_index == index && a.info_type == GetingeProductInfoTypeEnum.images.ToString()
                                              select a).FirstOrDefault();

            if (model != null)
            {
                model.info_content = imgUrl;
                model.info_date    = DateTime.Now;
                db.SaveChanges();
            }
            else
            {
                model                = new Getinge_Product_Info();
                model.info_type      = GetingeProductInfoTypeEnum.images.ToString();
                model.info_content   = imgUrl;
                model.product_id     = pId;
                model.info_img_index = index;
                model.info_date      = DateTime.Now;
                db.Getinge_Product_Info.Add(model);
                db.SaveChanges();
            }
            return(Json(new { code = 1, msg = imgUrl }));
        }
コード例 #17
0
        private protected void InsertFile(FileDto file, out Action revertCallback)
        {
            if (file is null)
            {
                throw new ArgumentNullException(nameof(file));
            }

            Base.EnsureCachePersistence(typeof(NoteDoc));
            var noteDocCache = Base.Caches[typeof(NoteDoc)];
            var noteDoc      = (NoteDoc)noteDocCache.CreateInstance();

            noteDoc.NoteID = file.EntityNoteId;
            noteDoc.FileID = file.FileId;
            noteDocCache.Insert(noteDoc);

            Base.EnsureCachePersistence(typeof(UploadFile));
            var uploadFileCache = Base.Caches[typeof(UploadFile)];
            var uploadFile      = (UploadFile)uploadFileCache.CreateInstance();

            uploadFile.FileID          = file.FileId;
            uploadFile.LastRevisionID  = 1;
            uploadFile.Versioned       = true;
            uploadFile.IsPublic        = false;
            uploadFile.Name            = file.FullName;
            uploadFile.PrimaryScreenID = PrimaryScreenID;
            uploadFileCache.Insert(uploadFile);

            Base.EnsureCachePersistence(typeof(UploadFileRevision));
            var fileRevisionCache = Base.Caches[typeof(UploadFileRevision)];
            var fileRevision      = (UploadFileRevision)fileRevisionCache.CreateInstance();

            fileRevision.FileID         = file.FileId;
            fileRevision.FileRevisionID = 1;
            fileRevision.Data           = file.Content;
            fileRevision.Size           = UploadFileHelper.BytesToKilobytes(file.Content.Length);
            fileRevisionCache.Insert(fileRevision);

            revertCallback = () =>
            {
                noteDocCache.SetStatus(noteDoc, PXEntryStatus.InsertedDeleted);
                uploadFileCache.SetStatus(uploadFile, PXEntryStatus.InsertedDeleted);
                fileRevisionCache.SetStatus(fileRevision, PXEntryStatus.InsertedDeleted);
            };
        }
コード例 #18
0
        public ActionResult SaveUserImag()
        {
            BizResultInfo result = UploadFileHelper.UploadFileToUserImg(Request);

            if (result.IsSuccess)
            {
                var loginEmail  = UILoginHelper.GetUIUserLoginNameOrEmail(HttpContext);
                var res         = UserInfoBo.GetUserInfoByLoginNameOrEmail(loginEmail);
                var bizUserInfo = res.Target as BizUserInfo;
                var path        = Server.MapPath(bizUserInfo.UserImagURL);
                if (System.IO.File.Exists(path))
                {
                    System.IO.File.Delete(path);
                }
                bizUserInfo.UserImagURL = result.ResultID;
                bizUserInfo.Save();
                result.SuccessMessage = "上传成功!";
            }
            return(Json(result));
        }
コード例 #19
0
        public void TestSave()
        {
            Mock <IAttachmentParentObject> mock = this.factory.CreateMock <IAttachmentParentObject>(); //产生一个mock对象

            mock.Expects.Between(0, 5).GetProperty(m => m.EntityId, "test_" + DateHelper.GetTimestamp());
            mock.Expects.Between(0, 5).GetProperty(m => m.EntityClassName, KernelContext.ParseObjectType(typeof(AttachmentParentObject)));
            mock.Expects.Between(0, 5).GetProperty(m => m.AttachmentEntityClassName, KernelContext.ParseObjectType(typeof(AttachmentFileInfo)));
            mock.Expects.Between(0, 5).GetProperty(m => m.AttachmentFolder, "test");

            IAttachmentParentObject parent = mock.MockObject;

            IAttachmentFileInfo param = new AttachmentFileInfo(parent);

            param.Id             = UploadFileHelper.NewIdentity();
            param.AttachmentName = "test_" + DateHelper.GetTimestamp();
            param.FileType       = ".txt";

            param = AttachmentStorageContext.Instance.AttachmentFileService.Save(param);

            Assert.IsNotNull(param);
        }
コード例 #20
0
        public async Task <ResponseModel> Handle(BufferedSingleFileUploadPhysicalCommand request, CancellationToken cancellationToken)
        {
            var errorModel      = new FormFileErrorModel();
            var formFileContent =
                await FileHelpers.ProcessFormFile <BufferedSingleFileUploadPhysical>(
                    request.File, errorModel, _permittedExtensions,
                    _defaultFileSizeLimit);

            if (errorModel.Errors.Any())
            {
                return(ResponseProvider.Ok(errorModel));
            }

            var filePath = UploadFileHelper.GetUploadAbsolutePath(_contentRootPath, request.File.FileName, request.Archive);

            using (var fileStream = File.Create(filePath))
            {
                await fileStream.WriteAsync(formFileContent, cancellationToken);
            }
            return(ResponseProvider.Ok("Upload file successful"));
        }
コード例 #21
0
        public async Task <Result <WxBackNewsShow> > GetBackNewsById([FromQuery] long id)
        {
            try
            {
                var item = await repo.FirstOrDefaultAsync <WxBackNewsShow>(x => x.Id == id);

                UpdBackNewsInfo(new List <WxBackNewsShow> {
                    item
                });
                item.UpFile = UploadFileHelper.GetUploadFileInfo(item.ImgUrlVir);
                return(new Result <WxBackNewsShow> {
                    IsSucc = true, Data = item
                });
            }
            catch (Exception ex)
            {
                logHelper.Error("GetBackNewsById:获取后台图文失败:" + ex.Message + "        " + ex.StackTrace);
            }

            return(new Result <WxBackNewsShow> {
                Message = "获取后台图文失败!"
            });
        }
コード例 #22
0
        private void CreateFile(PXGraph graph, Guid noteId, Guid newFileId, string name, byte[] content)
        {
            var noteDocCache = graph.Caches[typeof(NoteDoc)];
            var noteDoc      = (NoteDoc)noteDocCache.CreateInstance();

            noteDoc.NoteID = noteId;
            noteDoc.FileID = newFileId;
            noteDocCache.Insert(noteDoc);
            graph.EnsureCachePersistence(typeof(NoteDoc));

            var uploadFileCache = graph.Caches[typeof(CommonMailReceiveProvider.UploadFile)];
            var uploadFile      = (CommonMailReceiveProvider.UploadFile)uploadFileCache.CreateInstance();

            uploadFile.FileID         = newFileId;
            uploadFile.LastRevisionID = 1;
            uploadFile.Versioned      = true;
            uploadFile.IsPublic       = false;
            if (name.Length > 200)
            {
                name = name.Substring(0, 200);
            }
            uploadFile.Name            = newFileId + @"\" + name;
            uploadFile.PrimaryScreenID = "CR306015";             //TODO: need review
            uploadFileCache.Insert(uploadFile);
            graph.EnsureCachePersistence(typeof(CommonMailReceiveProvider.UploadFile));

            var fileRevisionCache = graph.Caches[typeof(UploadFileRevision)];
            var fileRevision      = (UploadFileRevision)fileRevisionCache.CreateInstance();

            fileRevision.FileID         = newFileId;
            fileRevision.FileRevisionID = 1;
            fileRevision.Data           = content;
            fileRevision.Size           = UploadFileHelper.BytesToKilobytes(content.Length);
            fileRevisionCache.Insert(fileRevision);
            graph.EnsureCachePersistence(typeof(UploadFileRevision));
        }
コード例 #23
0
        public ActionResult Save(IEnumerable <HttpPostedFileBase> attachment)
        {
            var result = UploadFileHelper.GetFileUpload(attachment);

            return(Json(new { Result = result, IsSuccess = result.Count() > 0, Invalid = true }, JsonRequestBehavior.AllowGet));
        }
        public async Task <ResponseModel <SingleUploadResponse> > Handle(SingleFileUploadPhysicalCommand request, CancellationToken cancellationToken)
        {
            var swTotalEncrypt = new Stopwatch();

            swTotalEncrypt.Start();
            var errorModel = new FormFileErrorModel();

            var multiPartContentTypeValidation = MultiPartContentTypeValidation(_accessor.HttpContext.Request.ContentType)
                                                 .Select(x => x.ErrorMessage)
                                                 .ToArray();

            if (multiPartContentTypeValidation.Any())
            {
                return(ResponseProvider.BadRequest <SingleUploadResponse>(multiPartContentTypeValidation));
            }

            var boundary = MultipartRequestHelper.GetBoundary(
                MediaTypeHeaderValue.Parse(_accessor.HttpContext.Request.ContentType),
                _defaultFormOptions.MultipartBoundaryLengthLimit);
            var reader  = new MultipartReader(boundary, _accessor.HttpContext.Request.Body);
            var section = await reader.ReadNextSectionAsync(cancellationToken);

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

                if (hasContentDispositionHeader)
                {
                    var hasFileContentDispositionValidation = HasFileContentDispositionValidation(contentDisposition)
                                                              .Select(x => x.ErrorMessage)
                                                              .ToArray();
                    if (hasFileContentDispositionValidation.Any())
                    {
                        return(ResponseProvider.BadRequest <SingleUploadResponse>(hasFileContentDispositionValidation));
                    }
                    else
                    {
                        var streamedFileContent = await FileHelpers.ProcessStreamedFile(
                            section, contentDisposition, errorModel,
                            _permittedExtensions, _streamFileLimitSize, ValidateExtension.Encrypt);

                        if (errorModel.Errors.Any())
                        {
                            //return ResponseProvider.BadRequest<SingleUploadResponse>(errorModel.Errors);
                            return(ResponseProvider.Ok(new SingleUploadResponse()));
                        }
                        var fileNameWithEncryptExtension = UploadFileHelper.GetFileNameWithEncryptExtension(request.File.FileName, request.EncryptAlg);
                        var uploadFileAbsolutePath       = UploadFileHelper.GetUploadAbsolutePath(_contentRootPath, fileNameWithEncryptExtension, request.Archive);

                        await UploadFile(streamedFileContent, uploadFileAbsolutePath, request.EncryptAlg);
                    }
                }

                section = await reader.ReadNextSectionAsync(cancellationToken);
            }
            swTotalEncrypt.Stop();

            var requestScheme = _accessor.HttpContext.Request.Scheme;
            var domain        = _accessor.HttpContext.Request.Host.Value;
            var url           = Path.Combine(requestScheme, domain, "Archive", request.Archive.ToString(), request.File.FileName);

            Console.Write($"File length: {request.File.Length / 1024f / 1024f} MB");
            Console.WriteLine($"Encrypt time: {swTotalEncrypt.ElapsedMilliseconds}");

            return(ResponseProvider.Ok(new SingleUploadResponse {
                Url = url
            }));
        }
コード例 #25
0
        public override void ProcessRequest(HttpContext context)
        {
            HttpRequest request = context.Request;

            HttpResponse response = context.Response;

            try
            {
                HttpPostedFile file = request.Files["fileData"];

                // 输出类型 id uri base64
                string outputType = request.Form["outputType"];

                string attachmentId              = request.Form["attachmentId"];
                string entityId                  = request.Form["entityId"];
                string entityClassName           = request.Form["entityClassName"];
                string attachmentEntityClassName = request.Form["attachmentEntityClassName"];
                string attachmentFolder          = request.Form["attachmentFolder"];

                // 匿名用户上传文件的文件, 存放在 anonymous 目录
                if (KernelContext.Current.User == null)
                {
                    attachmentFolder = "anonymous";
                }

                // IAttachmentParentObject parent = new AttachmentParentObject(entityId, entityClassName, attachmentEntityClassName, attachmentFolder);

                IAttachmentFileInfo attachment = UploadFileHelper.CreateAttachmentFile(
                    entityId,
                    entityClassName,
                    attachmentEntityClassName,
                    attachmentFolder,
                    file);

                // Office 在线客户端上传方式
                // 支持客户端赋值附件标识
                if (!string.IsNullOrEmpty(attachmentId))
                {
                    if (AttachmentStorageContext.Instance.AttachmentFileService.IsExist(attachmentId))
                    {
                        HttpContext.Current.Response.StatusCode        = 500;
                        HttpContext.Current.Response.StatusDescription = "Attachment id already exists.";
                        HttpContext.Current.Response.End();
                    }
                    else
                    {
                        attachment.Id = attachmentId;
                    }
                }

                // 检测文件最小限制
                if (attachment.FileSize < AttachmentStorageConfigurationView.Instance.AllowMinFileSize)
                {
                    HttpContext.Current.Response.StatusCode        = 500;
                    HttpContext.Current.Response.StatusDescription = "Attachment file size is too small.";
                    HttpContext.Current.Response.End();
                }

                // 检测文件最大限制
                if (attachment.FileSize > AttachmentStorageConfigurationView.Instance.AllowMaxFileSize)
                {
                    HttpContext.Current.Response.StatusCode        = 500;
                    HttpContext.Current.Response.StatusDescription = "Attachment file size is too big.";
                    HttpContext.Current.Response.End();
                }

                // 检测文件名后缀限制
                if (!Regex.IsMatch(attachment.FileType, AttachmentStorageConfigurationView.Instance.AllowFileTypes))
                {
                    HttpContext.Current.Response.StatusCode        = 500;
                    HttpContext.Current.Response.StatusDescription = "Attachment file type is invalid.";
                    HttpContext.Current.Response.End();
                }

                if (HttpContext.Current.Response.StatusCode != 500)
                {
                    attachment.Save();

                    KernelContext.Log.Info("attachment id: " + attachment.Id);

                    HttpContext.Current.Response.StatusCode = 200;

                    if (outputType == "uri")
                    {
                        // 输出 uri
                        HttpContext.Current.Response.Write(attachment.VirtualPath.Replace("{uploads}", AttachmentStorageConfigurationView.Instance.VirtualUploadFolder));
                    }
                    else
                    {
                        // 输出 id
                        HttpContext.Current.Response.Write(attachment.Id);
                    }
                }
            }
            catch (Exception ex)
            {
                // If any kind of error occurs return a 500 Internal Server error
                HttpContext.Current.Response.StatusCode        = 500;
                HttpContext.Current.Response.StatusDescription = "An error occured";
                HttpContext.Current.Response.End();

                KernelContext.Log.Error(ex.Message, ex);
            }
        }
コード例 #26
0
        public override void ProcessRequest(HttpContext context)
        {
            HttpRequest request = context.Request;

            HttpResponse response = context.Response;

            try
            {
                HttpPostedFile file = request.Files["fileData"];

                // 输出类型 id uri base64
                string outputType = request.Form["outputType"];

                string attachmentId              = request.Form["attachmentId"];
                string entityId                  = request.Form["entityId"];
                string entityClassName           = request.Form["entityClassName"];
                string attachmentEntityClassName = request.Form["attachmentEntityClassName"];
                string attachmentFolder          = request.Form["attachmentFolder"];

                // 调整图片大小
                int resize       = request.Form["resize"] == null ? 0 : Convert.ToInt32(request.Form["resize"]);
                int targetWidth  = request.Form["targetWidth"] == null ? 0 : Convert.ToInt32(request.Form["targetWidth"]);
                int targetHeight = request.Form["targetHeight"] == null ? 0 : Convert.ToInt32(request.Form["targetHeight"]);

                // 设置图片缩略图
                int thumbnail       = request.Form["thumbnail"] == null ? 0 : Convert.ToInt32(request.Form["thumbnail"]);
                int thumbnailWidth  = request.QueryString["targetWidth"] == null ? 100 : Convert.ToInt32(request.QueryString["thumbnailWidth"]);
                int thumbnailHeight = request.QueryString["thumbnailHeight"] == null ? 100 : Convert.ToInt32(request.QueryString["thumbnailHeight"]);

                // 匿名用户上传文件的文件, 存放在 anonymous 目录
                if (KernelContext.Current.User == null)
                {
                    attachmentFolder = "anonymous";
                }

                IAttachmentFileInfo attachment = UploadFileHelper.CreateAttachmentFile(
                    entityId,
                    entityClassName,
                    attachmentEntityClassName,
                    attachmentFolder,
                    file);

                // Office 在线客户端上传方式
                // 支持客户端赋值附件标识
                if (!string.IsNullOrEmpty(attachmentId))
                {
                    if (AttachmentStorageContext.Instance.AttachmentFileService.IsExist(attachmentId))
                    {
                        HttpContext.Current.Response.StatusCode        = 500;
                        HttpContext.Current.Response.StatusDescription = "Attachment id already exists.";
                        HttpContext.Current.Response.End();
                    }
                    else
                    {
                        attachment.Id = attachmentId;
                    }
                }

                // 检测文件最小限制
                if (attachment.FileSize < AttachmentStorageConfigurationView.Instance.AllowMinFileSize)
                {
                    HttpContext.Current.Response.StatusCode        = 500;
                    HttpContext.Current.Response.StatusDescription = "Attachment file size is too small.";
                    HttpContext.Current.Response.End();
                }

                // 检测文件最大限制
                if (attachment.FileSize > AttachmentStorageConfigurationView.Instance.AllowMaxFileSize)
                {
                    HttpContext.Current.Response.StatusCode        = 500;
                    HttpContext.Current.Response.StatusDescription = "Attachment file size is too big.";
                    HttpContext.Current.Response.End();
                }

                // 检测文件名后缀限制
                if (!Regex.IsMatch(attachment.FileType, AttachmentStorageConfigurationView.Instance.AllowFileTypes))
                {
                    HttpContext.Current.Response.StatusCode        = 500;
                    HttpContext.Current.Response.StatusDescription = "Attachment file type is invalid.";
                    HttpContext.Current.Response.End();
                }

                if (HttpContext.Current.Response.StatusCode != 500)
                {
                    // 调整图片大小
                    if (resize == 1)
                    {
                        Image image = Image.FromStream(ByteHelper.ToStream(attachment.FileData));

                        attachment.FileData = ThumbnailManagement.Resize(image, attachment.FileType, targetWidth, targetHeight);
                    }

                    if (outputType == "base64")
                    {
                        // 输出 Base64
                        HttpContext.Current.Response.StatusCode = 200;

                        HttpContext.Current.Response.Write(ByteHelper.ToBase64(attachment.FileData));
                    }
                    else
                    {
                        attachment.Save();

                        // 调整图片大小
                        if (thumbnail == 1)
                        {
                            Image image = Image.FromStream(ByteHelper.ToStream(attachment.FileData));

                            attachment.FileData = ThumbnailManagement.Resize(image, attachment.FileType, thumbnailWidth, thumbnailHeight);

                            var fileName = string.Format("{0}_{1}x{2}{3}", attachment.Id, thumbnailWidth, thumbnailHeight, attachment.FileType);

                            Stream stream = ByteHelper.ToStream(attachment.FileData);

                            // 创建缩略图
                            ThumbnailManagement.CreateThumbnail(attachment.Id, stream, attachment.FileType, thumbnailWidth, thumbnailHeight);
                        }

                        HttpContext.Current.Response.StatusCode = 200;

                        if (outputType == "uri")
                        {
                            // 输出 uri
                            HttpContext.Current.Response.Write(attachment.VirtualPath.Replace("{uploads}", AttachmentStorageConfigurationView.Instance.VirtualUploadFolder));
                        }
                        else
                        {
                            // 输出 id
                            HttpContext.Current.Response.Write(attachment.Id);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                // If any kind of error occurs return a 500 Internal Server error
                HttpContext.Current.Response.StatusCode        = 500;
                HttpContext.Current.Response.StatusDescription = "An error occured";
                HttpContext.Current.Response.End();

                KernelContext.Log.Error(ex.Message, ex);
            }
        }
コード例 #27
0
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";

            try
            {
                HttpPostedFile file = context.Request.Files["Filedata"];

                if (file != null)
                {
                    //判断图片长宽是否符合标准

                    System.Drawing.Image fristImage = System.Drawing.Image.FromStream(file.InputStream);
                    if (fristImage.Width < 224 || fristImage.Height < 224)
                    {
                        context.Response.Write("sizeError");
                    }
                    else
                    {
                        //上传图片的扩展名
                        string fileExtension = Path.GetExtension(file.FileName);//上传文件的后缀
                        //判断文件格式
                        if (!CheckValidExt(fileExtension))
                        {
                            context.Response.Write("错误提示:文件格式不正确!" + fileExtension);
                            return;
                        }
                        //根目录文件名称
                        string folder_name = context.Request["folder_name"].ToString();

                        //使用时间+随机数重命名文件
                        string strDateTime = DateTime.Now.ToString("yyMMddhhmmssfff"); //取得时间字符串
                        Random ran         = new Random();
                        string strRan      = Convert.ToString(ran.Next(100, 999));     //生成三位随机数
                        string saveName    = strDateTime + strRan + fileExtension;

                        string UploadDir = UploadFileHelper.GetUploadImgPre(HttpContext.Current.Request.Url.ToString());
                        string path      = DateTime.Now.ToString("yyyy") + "/" + DateTime.Now.ToString("MM") + "/" + DateTime.Now.ToString("dd");

                        string imgPath = UploadDir + folder_name + "/" + path;

                        imgPath = imgPath.Replace("\\", "/");

                        //判断是否有该文件夹,没有就创建
                        if (!Directory.Exists(imgPath))
                        {
                            Directory.CreateDirectory(imgPath);
                        }

                        file.SaveAs(imgPath + "/" + saveName);

                        System.Drawing.Image imgPhoto = System.Drawing.Image.FromFile(imgPath + "/" + saveName);
                        int intHeight = imgPhoto.Height; //图片的高
                        int intWidth  = imgPhoto.Width;  //图片的宽度

                        string showimg = UploadFileHelper.GetCofigShowUrl();
                        //下面这句代码缺少的话,上传成功后上队列的显示不会自动消失
                        context.Response.Write("{path:'" + showimg + folder_name + "/" + path + "/" + saveName + "',jdpath:'" + folder_name + "/" + path + "/" + saveName + "',height:'" + intHeight + "',width:'" + intWidth + "'}");
                    }
                }
                else
                {
                    context.Response.Write("0");
                }
            }
            catch (Exception ex)
            {
                context.Response.Write(ex.ToString());
            }
        }
コード例 #28
0
        /// <summary>
        /// 文件上传
        /// </summary>
        /// <param name="postedFile">文件类</param>
        /// <param name="configPath">保存路径</param>
        /// <param name="?"></param>
        /// <param name="?"></param>
        public bool UpLoad(string type, HttpPostedFileBase postedFile, string configPath, string filename, out string path, out string str)
        {
            bool   flag       = true;
            string savepath   = System.Web.HttpContext.Current.Server.MapPath(configPath); //获取保存路径
            string sExtension = filename.Substring(filename.LastIndexOf('.'));             //获取拓展名

            savepath += "/" + DateTime.Now.ToString("yyyy") + "/" + DateTime.Now.ToString("MM");
            if (!Directory.Exists(savepath))
            {
                Directory.CreateDirectory(savepath);
            }
            string sNewFileName = DateTime.Now.ToString("yyyyMMdd-" + Guid.NewGuid().ToString());

            path = savepath + @"/" + sNewFileName + sExtension;//保存路径
            string message = "";

            switch (type)
            {
            case "EDynamic":    //文章资讯
                if (UploadFileHelper.UploadImg(postedFile, path, 500, out message))
                {
                    path = configPath + DateTime.Now.ToString("yyyy") + "/" + DateTime.Now.ToString("MM") + @"/" + sNewFileName + sExtension;
                }
                else
                {
                    flag = false;
                }
                break;

            case "EDocument":    //文档列表
                if (UploadFileHelper.UploadImg(postedFile, path, 500, out message))
                {
                    path = configPath + DateTime.Now.ToString("yyyy") + "/" + DateTime.Now.ToString("MM") + @"/" + sNewFileName + sExtension;
                }
                else
                {
                    flag = false;
                }
                break;

            case "Advertise":    //品牌
                if (UploadFileHelper.UploadImg(postedFile, path, 500, out message))
                {
                    path = configPath + DateTime.Now.ToString("yyyy") + "/" + DateTime.Now.ToString("MM") + @"/" + sNewFileName + sExtension;
                }
                else
                {
                    flag = false;
                }
                break;

            case "ShopCategory":    //商品类型上传
                string SmallPath = savepath + "/SmallPath/";
                if (!Directory.Exists(SmallPath))
                {
                    Directory.CreateDirectory(SmallPath);
                }
                SmallPath = SmallPath + @"/" + sNewFileName + sExtension;
                if (UploadFileHelper.UploadSmallImg(postedFile, path, SmallPath, 150, 150, 500, out message))
                {
                    path = configPath + DateTime.Now.ToString("yyyy") + "/" + DateTime.Now.ToString("MM") + @"/" + sNewFileName + sExtension;
                }
                else
                {
                    flag = false;
                }
                break;

            case "Company":    //公司和商家图片上传
                if (UploadFileHelper.UploadImg(postedFile, path, 500, out message))
                {
                    path = configPath + DateTime.Now.ToString("yyyy") + "/" + DateTime.Now.ToString("MM") + @"/" + sNewFileName + sExtension;
                }
                else
                {
                    flag = false;
                }
                break;

            case "News":    //新闻图片
                if (UploadFileHelper.UploadImg(postedFile, path, 500, out message))
                {
                    path = configPath + DateTime.Now.ToString("yyyy") + "/" + DateTime.Now.ToString("MM") + @"/" + sNewFileName + sExtension;
                }
                else
                {
                    flag = false;
                }
                break;
            }
            str = message;//返回错误信息
            return(flag);
        }
コード例 #29
0
        public ActionResult UploadToTask(int ProjectID, int?TaskID, string TaskName)
        {
            BuildingEntities db   = (BuildingEntities)this.db;
            User             user = HttpContext.CurrentUser();

            if (Request.Files.Count < 1)
            {
                return(Json(new { Code = 202, Success = false, Message = "No files uploaded!" }));
            }

            Project project = db.Projects.FirstOrDefault(val => val.ID == ProjectID);

            if (project == null)
            {
                return(Json(new { Code = 202, Success = false, Message = "Project not found!" }));
            }

            CheckPermissionsEventArgs e = new CheckPermissionsEventArgs(db, "Projects", "Project", project, EntityJs.Client.Events.ActionsEnum.Select);

            project.OnCheckPermissions(e);
            if (e.Cancel)
            {
                return(Json(new { Code = 202, Success = false, Message = "You can't operate with this project!" }));
            }

            ProjectTask task = null;

            if (TaskID > 0)
            {
                task = db.ProjectTasks.FirstOrDefault(val => val.ID == TaskID);
                if (task == null)
                {
                    return(Json(new { Code = 202, Success = false, Message = "Task not found!" }));
                }

                e = new CheckPermissionsEventArgs(db, "ProjectTasks", "ProjectTask", task, EntityJs.Client.Events.ActionsEnum.Edit);
                task.OnCheckPermissions(e);
                if (e.Cancel)
                {
                    return(Json(new { Code = 202, Success = false, Message = "You can't edit this task!" }));
                }
            }

            int              code;
            string           message;
            UploadFileHelper helper = new UploadFileHelper(this.db as BuildingEntities);

            Folder folder = helper.GetFolder(project, TaskName, true);

            Models.File        file  = helper.UploadFiles(-1, folder.ID, out code, out message, false);
            Models.ProjectFile pfile = file != null?file.ProjectFiles.FirstOrDefault(val => val.ProjectID == ProjectID) : null;

            if (pfile != null)
            {
                pfile.ProjectTask = task;
                db.SaveChanges();
            }
            var data = new { Code = code, Message = message, File = file != null?file.ToJson() : null, ProjectFile = pfile != null?pfile.ToJson() : null };

            return(this.Json(data));
        }
コード例 #30
0
 public ActionResult Remove(string realName)
 {
     return(Json(new { IsSuccess = UploadFileHelper.RemoveFileUpload(realName), Invalid = true }, JsonRequestBehavior.AllowGet));
 }