Exemplo n.º 1
0
        /// <summary>
        /// 文件上传
        /// </summary>
        /// <param name="hfc">客户端上传文件流</param>
        /// <param name="afterPath">类似:aaaa/bbb/子文件夹</param>
        /// <returns></returns>
        public static List<string> MvcUpload(HttpFileCollectionBase hfc, string afterPath = "")
        {
            string path = UploadRoot + afterPath;

            List<string> theList = new List<string>();
            string filePath = HttpContext.Current.Server.MapPath(path);
            if (!Directory.Exists(filePath))
            {
                Directory.CreateDirectory(filePath);
            }

            foreach (string item in hfc)
            {
                if (hfc[item] == null || hfc[item].ContentLength == 0) continue;
                try
                {
                    string fileExtension = Path.GetExtension(hfc[item].FileName);
                    var fileName = Guid.NewGuid().ToString() + fileExtension;
                    hfc[item].SaveAs(filePath + fileName);

                    string strSqlPath = (path + fileName).Replace("~/", ServerHost);
                    theList.Add(strSqlPath);
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.Write(ex);
                }
            }
            return theList;
        }
Exemplo n.º 2
0
        /// <summary>
        /// 单个文件上传(只获取第一个文件,返回的文件名是文件的md5值),返回为json数据格式,成功返回{status:"success",website:"a.jpg"},失败,返回{status:"error",website:"error"}
        /// </summary>
        /// <param name="context">上下文</param>
        /// <param name="FilePath">文件路径</param>
        /// <param name="outFileName">返回文件的md5</param>
        /// <returns>返回json状态信息</returns>
        public static bool FileUploadSingle(HttpFileCollectionBase files, string FilePath, out string outFileName)
        {
            //string json = "";
            //找到目标文件对象
            HttpFileCollectionBase hfc = files;
            HttpPostedFileBase hpf = hfc[0];

            if (hpf.ContentLength > 0)
            {
                //根据文件的md5的hash值做文件名,防止文件的重复和图片的浪费
                string FileName = CreateFileForFileNameByMd5(hpf.FileName); //CreateDateTimeForFileName(hpf.FileName);//自动生成文件名

                string file = System.IO.Path.Combine(FilePath,
                 FileName);
                if (!Directory.Exists(Path.GetDirectoryName(file)))
                {
                    Directory.CreateDirectory(file);
                }
                hpf.SaveAs(file);
                //此处改为返回filePath,回显图片更新页面Image的src
                //json = "{status:\"success\", fileName:\"" + FileName+ "\" ,filePath:\"" + FilePath + "\"}";
                outFileName = FileName;
                return true;
            }
            else
            {
                //json = "{status:\"error\", fileName:\"error\", filePath:\"error\"}";
                outFileName = FilePath;
                return false;
            }

            //return json;
        }
Exemplo n.º 3
0
        public static void SendMailToSiteManager(this Site site, string from, string subject, string body, bool isBodyHtml, HttpFileCollectionBase files = null)
        {
            var smtp = site.Smtp;
            if (smtp == null)
            {
                throw new ArgumentNullException("smtp");
            }

            MailMessage message = new MailMessage() { From = new MailAddress(from) };
            foreach (var item in smtp.To)
            {
                if (!string.IsNullOrEmpty(item))
                {
                    message.To.Add(item);
                }
            }
            message.Subject = subject;
            message.Body = body;

            message.IsBodyHtml = isBodyHtml;

            if (files != null && files.Count > 0)
            {
                foreach (string key in files.AllKeys)
                {
                    HttpPostedFileBase file = files[key] as HttpPostedFileBase;

                    message.Attachments.Add(new Attachment(file.InputStream, file.FileName, IO.IOUtility.MimeType(file.FileName)));
                }
            }

            SmtpClient smtpClient = smtp.ToSmtpClient();

            smtpClient.Send(message);
        }
Exemplo n.º 4
0
        private static List<HttpPostedFileBase> GetFiles(HttpFileCollectionBase fileCollection, string key) {
            // first, check for any files matching the key exactly
            List<HttpPostedFileBase> files = fileCollection.AllKeys
                .Select((thisKey, index) => (String.Equals(thisKey, key, StringComparison.OrdinalIgnoreCase)) ? index : -1)
                .Where(index => index >= 0)
                .Select(index => fileCollection[index])
                .ToList();

            if (files.Count == 0) {
                // then check for files matching key[0], key[1], etc.
                for (int i = 0; ; i++) {
                    string subKey = String.Format(CultureInfo.InvariantCulture, "{0}[{1}]", key, i);
                    HttpPostedFileBase thisFile = fileCollection[subKey];
                    if (thisFile == null) {
                        break;
                    }
                    files.Add(thisFile);
                }
            }

            // if an <input type="file" /> element was rendered on the page but the user did not select a file before posting
            // the form, null out that entry in the list.
            List<HttpPostedFileBase> filteredFiles = files.ConvertAll((Converter<HttpPostedFileBase, HttpPostedFileBase>)ChooseFileContentOrNull);
            return filteredFiles;
        }
Exemplo n.º 5
0
        private OFormResultRecord SaveFormToDB(OFormPart form, Dictionary<string, string> postData, HttpFileCollectionBase files, string ipSubmiter)
        {
            var xdoc = ConvertToXDocument(postData);
            var resultRecord = new OFormResultRecord
            {
                Xml = xdoc.ToString(),
                CreatedDate = DateTime.UtcNow,
                Ip = ipSubmiter,
                CreatedBy = postData[OFormGlobals.CreatedByKey]
            };

            if (form.CanUploadFiles && files.Count > 0)
            {
                foreach (string key in files.Keys)
                {
                    if (files[key].ContentLength == 0) { continue; }

                    CheckFileSize(form, files[key]);
                    CheckFileType(form, files[key]);

                    var formFile = SaveFile(key, files[key]);
                    resultRecord.AddFile(formFile);
                }
            }

            this._resultRepo.Create(resultRecord);
            form.Record.AddFormResult(resultRecord);
            _contentManager.Flush();

            return resultRecord;
        }
Exemplo n.º 6
0
 // Methods
 public CmisHttpFileCollectionWrapper(HttpFileCollectionBase files)
 {
     foreach (var key in files.AllKeys)
     {
         this.AddFile(key, files[key]);
     }
 }
Exemplo n.º 7
0
        public string Create(
            Entity entity,
            FormCollection collection,
            HttpFileCollectionBase files)
        {
            var entityRecord = entity.CreateRecord(collection, files, x => x.OnCreateDefaultValue);
            if (_validator.Validate(entityRecord) == false)
            {
                _notificator.Error(IlaroAdminResources.RecordNotValid);
                return null;
            }
            var existingRecord = _source.GetRecord(
                entity,
                entityRecord.Keys.Select(value => value.AsObject).ToArray());
            if (existingRecord != null)
            {
                _notificator.Error(IlaroAdminResources.EntityAlreadyExist);
                return null;
            }

            var propertiesWithUploadedFiles = _filesHandler.Upload(
                entityRecord,
                x => x.OnCreateDefaultValue);

            var id = _creator.Create(
                entityRecord,
                () => _changeDescriber.CreateChanges(entityRecord));

            if (id.IsNullOrWhiteSpace() == false)
                _filesHandler.ProcessUploaded(propertiesWithUploadedFiles);
            else
                _filesHandler.DeleteUploaded(propertiesWithUploadedFiles);

            return id;
        }
Exemplo n.º 8
0
        public void Attach(int postId, int courseId, HttpFileCollectionBase files)
        {
            CheckAccessToPost(postId);

            if (files.Count == 0)
                return;

            for (var i = 0; i < files.Count; i++)
            {
                if (files[i] == null) continue;
                if (files[i].ContentLength > 29 * 1024 * 1024) continue; // 100 MB

                var identifier = Guid.NewGuid();
                var guidName = identifier.ToString();

                var courseDirectory = GetCourseDirectory(courseId);

                var extention = Path.GetExtension(files[i].FileName);

                var path = Path.Combine(courseDirectory, guidName + extention);

                files[i].SaveAs(path);

                Repository.Add(new Entities.File()
                {
                    Name = files[i].FileName.Substring(0, files[i].FileName.Length < 100 ? files[i].FileName.Length  : 100),
                    Path = path,
                    PostId = postId,
                    Identifier = identifier
                });
            }

            Repository.Save();
        }
Exemplo n.º 9
0
        public string Create(
            Entity entity,
            FormCollection collection,
            HttpFileCollectionBase files)
        {
            entity.Fill(collection, files);
            if (_validator.Validate(entity) == false)
            {
                _notificator.Error("Not valid");
                return null;
            }
            var existingRecord = _source.GetRecord(entity, entity.Key.Select(x => x.Value.AsObject));
            if (existingRecord != null)
            {
                _notificator.Error(IlaroAdminResources.EntityAlreadyExist);
                return null;
            }

            var propertiesWithUploadedFiles = _filesHandler.Upload(entity);

            var id = _creator.Create(entity, () => _changeDescriber.CreateChanges(entity));

            if (id.IsNullOrWhiteSpace() == false)
                _filesHandler.ProcessUploaded(propertiesWithUploadedFiles);
            else
                _filesHandler.DeleteUploaded(propertiesWithUploadedFiles);

            return id;
        }
        public JsonResult PublishDingApp(DingAppViewModel model)
        {
            ActionResult result;

            //数据验证
            result = ValideDingApp(model);
            System.Web.HttpFileCollectionBase files = HttpContext.Request.Files;
            if (files.Count > 0 && files[0].ContentLength > 1024 * 1024)
            {
                result.Success = false;
                result.Message = "msgGlobalString.ImageMaxLength";
                return(Json(result, "text/html"));
            }
            //获取钉钉微应用头像附件ID
            string attchmentId = Engine.SettingManager.GetCustomSetting(CustomSetting.Setting_DDMediaId);

            if (files.Count > 0 && !string.IsNullOrEmpty(files[0].FileName))
            {
                //ID为空则新建
                attchmentId = attchmentId ?? Guid.NewGuid().ToString();
                SaveImage(files, attchmentId, attchmentId);
                Engine.SettingManager.SetCustomSetting(CustomSetting.Setting_DDMediaId, attchmentId);
            }
            if (string.IsNullOrEmpty(attchmentId))
            {
                result.Success = false;
                result.Message = "msgGlobalString.ImgNotEmpty";
                return(Json(result, "text/html"));
            }
            //更新附件中的DingTalkMediaID
            this.Engine.DingTalkAdapter.GetAttachmentDingTalkViewUrl(this.UserValidator.UserID, DingTalkAdapter.Param_DingTalkCode, attchmentId, attchmentId);
            Attachment attachment = this.Engine.BizObjectManager.GetAttachment(this.UserValidator.UserID, DingTalkAdapter.Param_DingTalkCode, attchmentId, attchmentId);

            if (string.IsNullOrEmpty(attachment.DingTalkMediaID))
            {
                result.Success = false;
                result.Message = "msgGlobalString.ImgNotEmpty";
                return(Json(result, "text/html"));
            }
            //钉钉微应用设置
            Engine.SettingManager.SetCustomSetting(CustomSetting.Setting_DDAppName, model.AppName);
            Engine.SettingManager.SetCustomSetting(CustomSetting.Setting_DDAppDesc, model.AppDesc);
            Engine.SettingManager.SetCustomSetting(CustomSetting.Setting_DDAppHomeUrl, model.HomeUrl);
            Engine.SettingManager.SetCustomSetting(CustomSetting.Setting_DDAppPcUrl, model.PcUrl);
            Engine.SettingManager.SetCustomSetting(CustomSetting.Setting_DDOmpLink, model.OmpLink);
            DingTalkMicroApp dingApp = this.Engine.DingTalkAdapter.CreateMicroApp(attachment.DingTalkMediaID, model.AppName, model.AppDesc, model.HomeUrl, model.PcUrl, model.OmpLink);

            if (dingApp.errcode != "0")
            {
                result.Success = false;
                result.Message = "msgGlobalString.PublishFailed";
            }
            else
            {
                Engine.SettingManager.SetCustomSetting(CustomSetting.Setting_DDAppAgentId, dingApp.agentid);
            }
            result.Extend = dingApp;
            return(Json(result, "text/html", JsonRequestBehavior.AllowGet));
        }
Exemplo n.º 11
0
        protected virtual void SendMail(ControllerContext controllerContext, Site site, ContactSiteModel ContactSiteModel, HttpFileCollectionBase files) {

            var from = ContactSiteModel.From;
            var subject = ContactSiteModel.Subject;
            var body = string.Format(ContactSiteModel.EmailBody ,ContactSiteModel.From, ContactSiteModel.Subject, ContactSiteModel.Body);

            site.SendMailToSiteManager(from, subject, body, true , files);
        }
Exemplo n.º 12
0
 // Methods
 public HttpFileCollectionBaseWrapper(HttpFileCollectionBase httpFileCollection)
 {
     if (httpFileCollection == null)
     {
         throw new ArgumentNullException("httpFileCollection");
     }
     this._collection = httpFileCollection;
 }
Exemplo n.º 13
0
 public static EntityRecord CreateRecord(
     this Entity entity,
     IValueProvider valueProvider,
     HttpFileCollectionBase files,
     Func<Property, object> defaultValueResolver = null)
 {
     return EntityRecordCreator.CreateRecord(entity, valueProvider, files, defaultValueResolver);
 }
Exemplo n.º 14
0
 public Uploader(ILogger logger, AreaRegistration area, HttpFileCollectionBase files, string tenant,
     string[] allowedExtensions)
 {
     this.Logger = logger;
     this.Area = area;
     this.Files = files;
     this.Tenant = tenant;
     this.AllowedExtensions = allowedExtensions;
 }
        public void SetUp()
        {
            mocks = new MockRepository();
            file = mocks.DynamicMock<HttpPostedFileBase>();

            var collection = new WriteableHttpFileCollection();
            readWrite = collection;
            readOnly = collection;
        }
Exemplo n.º 16
0
		public string Upload(string destinationPath, HttpFileCollectionBase files)
		{
			if (CustomException != null)
				throw CustomException;

			if (files.Count > 0)
				return files[files.Count - 1].FileName;
			else
				return "";
		}
Exemplo n.º 17
0
        internal UploadedFileCollection(HttpFileCollectionBase collection)
        {
            if (collection == null)
            {
                throw new ArgumentNullException("collection");
            }

            m_collection = new List<IUploadedFile>();

            PopulateFiles(collection);
        }
Exemplo n.º 18
0
 public void CreateAttachments(HttpFileCollectionBase files, int postID)
 {
     foreach (string filename in files)
     {
         HttpPostedFileBase f = files[filename];
         if (f.ContentLength > 0)
         {
             CreateAttachment(f, postID);
         }
     }
 }
Exemplo n.º 19
0
        public static Boolean isImageFound(HttpFileCollectionBase files)
        {
            foreach (string file in files)
            {
                HttpPostedFileBase hpf = (HttpPostedFileBase)files[file];

                if (hpf.ContentLength == 0)
                    return false;
            }

            return true;
        }
Exemplo n.º 20
0
        public static MarketingCampaign CreateMarketingCampaign(string companyName, string website, string city, string country,
            string username, string email, string phone, HttpFileCollectionBase postedFiles, string description,
            HttpPostedFileBase logoFile, string referringURL, Action<EntityContext, Company> createPortfolios)
        {
            var context = new Entities();

            if (Account.Exists(username))
                throw new Exception("The username already exists.");

            var account = new Account();
            account.Username = username;
            account.Password = AgileFx.Security.CryptoUtil.HashPassword(Guid.NewGuid().ToString());
            account.Status = ACCOUNT_STATUS.ACTIVE;
            account.LastLoginDate = DateTime.Now;
            account.DateAdded = DateTime.Now;
            account.Type = ACCOUNT_TYPE.COMPANY;
            account.Email = email;

            var company = new Company();
            company.Account = account;
            company.Name = companyName;
            company.Website = website;
            company.City = city;
            company.Country = country;
            company.Phone = phone;

            if (logoFile.ContentLength > 0)
                company.SaveLogo(logoFile);

            company.Description = description;

            foreach (var tag in context.Tag.Where(t => t.Name == "Web Design" || t.Name == ""))
                company.Tags.Add(tag);

            createPortfolios(context, company);

            context.AddObject(company);
            context.SaveChanges();

            var marketingCamp = new MarketingCampaign();
            marketingCamp.Account = account.Id;
            marketingCamp.DateCreated = DateTime.UtcNow;
            marketingCamp.DateModified = DateTime.UtcNow;
            marketingCamp.ReferringURL = referringURL;
            marketingCamp.Status = MARKETING_CAMPAIGN_STATUS.NEW;
            marketingCamp.Token = Guid.NewGuid();

            context.AddObject(marketingCamp);
            context.SaveChanges();

            return marketingCamp;
        }
Exemplo n.º 21
0
        public int AddPhoto(System.Web.HttpFileCollectionBase files, string albumName)
        {
            int   albumId = db.Albums.Where(a => a.Name == albumName).Select(a => a.Id).First();
            Photo photo   = db.Photos.Add(new Photo
            {
                Date    = DateTime.Now.ToShortDateString(),
                AlbumId = albumId
            });

            db.SaveChanges();
            UploadImage(files, photo.Id);
            return(photo.Id);
        }
Exemplo n.º 22
0
        /// <summary>
        /// Uploads a colletion of files to the image server
        /// </summary>
        /// <param name="files">the files to upload</param>
        /// <param name="imagePath">The path to save the image to</param>
        /// <returns>list of result objects with filename and success / fail messages</returns>
        public IList<ImageUploadResult> UploadImages(HttpFileCollectionBase files, string imagePath)
        {
            // Upload hte image to the storage
            IList<ImageUploadResult> results = this._imageStorage.UploadImages(files, this._website.Domain, imagePath);

            foreach (ImageUploadResult result in results)
            {
                Image image = this.SaveImage(new Image(result, this._website.Id));
                result.ImageId = image.Id;
            }

            return results;
        }
Exemplo n.º 23
0
        public JsonResult UploadFile()
        {
            System.Web.HttpFileCollectionBase files = HttpContext.Request.Files; files = Request.Files;
            if (files == null || files.Count == 0)
            {
                return(null);
            }
            string attachmentId = Guid.NewGuid().ToString();

            for (int i = 0; i < files.Count; i++)
            {
                HttpPostedFileBase file = files[i] as System.Web.HttpPostedFileBase;
                if (file.ContentLength == 0)
                {
                    continue;
                }
                if (this.IsPostForm)
                {
                    attachmentId = files.AllKeys[i];
                }

                int checkResult = this.CheckFile(file);
                if (checkResult != 0 && checkResult != 1)
                {
                    //检查失败
                    var result = new HandlerResult(this.FileID, string.Empty, checkResult);
                    return(Json(result));
                }
                if (!string.IsNullOrEmpty(this.BizObjectID))
                {
                    if (this.Engine.BizObjectManager.GetAttachmentHeader(this.SchemaCode, this.BizObjectID, attachmentId) != null)
                    {
                        continue;
                    }
                }
                UploadFile(file, attachmentId);
            }

            if (!this.IsPostForm)
            {
                string url = AppConfig.GetReadAttachmentUrl(
                    this.IsMobile,
                    this.SchemaCode,
                    "",
                    attachmentId);
                var result = new HandlerResult(this.FileID, attachmentId, url);
                return(Json(result));
            }

            return(null);
        }
Exemplo n.º 24
0
        public JsonResult UploadDoc()
        {
            string fname = "";
            List <SessionListnew> list = Session["SesDet"] as List <SessionListnew>;
            string _imgname            = string.Empty;

            if (Request.Files.Count > 0)
            {
                try
                {
                    //  Get all files from Request object
                    System.Web.HttpFileCollectionBase files = Request.Files;
                    for (int i = 0; i < files.Count; i++)
                    {
                        //string path = AppDomain.CurrentDomain.BaseDirectory + "Uploads/";
                        //string filename = Path.GetFileName(Request.Files[i].FileName);

                        HttpPostedFileBase file = files[i];


                        // Checking for Internet Explorer
                        if (Request.Browser.Browser.ToUpper() == "IE" || Request.Browser.Browser.ToUpper() == "INTERNETEXPLORER")
                        {
                            string[] testfiles = file.FileName.Split(new char[] { '\\' });
                            fname = testfiles[testfiles.Length - 1];
                        }
                        else
                        {
                            fname = file.FileName;
                            var _ext = Path.GetExtension(fname);
                        }

                        // Get the complete folder path and store the file inside it.
                        _imgname = Path.Combine(Server.MapPath("/Uploads/"), fname);
                        file.SaveAs(_imgname);
                    }
                    // Returns message that successfully uploaded
                    return(Json(fname, JsonRequestBehavior.AllowGet));
                }
                catch (Exception ex)
                {
                    return(Json("Error occurred. Error details: " + ex.Message));
                }
            }
            else
            {
                return(Json(fname, JsonRequestBehavior.AllowGet));
            }
            // return Json(Convert.ToString(_imgname), JsonRequestBehavior.AllowGet);
        }
Exemplo n.º 25
0
        /// <summary>
        /// 判断上传文件组里的文件大小是否超过最大值
        /// </summary>
        /// <param name="files">上传的文件组</param>
        /// <returns>超过最大值返回false,否则返回true.</returns>
        public static bool IsAllowedLengthForFiles(HttpFileCollectionBase files)
        {
            for (int i = 0; i < files.Count; i++)
            {
                HttpPostedFileBase file = files[i];

                if (!IsAllowedLengthForFile(file))
                {
                    return false;
                }
            }

            return true;
        }
Exemplo n.º 26
0
        public void Processing(System.Web.HttpFileCollectionBase collection)
        {
            System.Threading.Tasks.Parallel.ForEach(collection.AllKeys, (file) =>
            {
                System.Web.HttpPostedFileBase upload = collection[file];
                lock (this.lockObject)
                {
                    byte[] arrayBytes = new byte[upload.ContentLength];
                    upload.InputStream.Read(arrayBytes, 0, arrayBytes.Length);
                    this.dictionary.Add(upload.FileName, arrayBytes);
                }
            });

            ProcessingFiles();
        }
Exemplo n.º 27
0
        public static void SendMailToCustomer(this Site site, string to, string subject, string body, bool isBodyHtml, HttpFileCollectionBase files = null)
        {
            var smtp = site.Smtp;
            if (smtp == null)
            {
                throw new ArgumentNullException("smtp");
            }

            MailMessage message = new MailMessage() { From = new MailAddress(smtp.From) };
            message.To.Add(to);
            message.Subject = subject;
            message.Body = body;
            message.IsBodyHtml = isBodyHtml;
            SmtpClient smtpClient = smtp.ToSmtpClient();

            smtpClient.Send(message);
        }
Exemplo n.º 28
0
        public static EntityRecord CreateRecord(
            Entity entity,
            IValueProvider valueProvider,
            HttpFileCollectionBase files,
            Func<Property, object> defaultValueResolver = null)
        {
            var entityRecord = new EntityRecord(entity);
            foreach (var property in entity.Properties.DistinctBy(x => x.Column))
            {
                var propertyValue = property.TypeInfo.IsFile ?
                    GetPropertyValueForFile(property, valueProvider, files) :
                    GetPropertyValue(property, valueProvider, defaultValueResolver);
                entityRecord.Values.Add(propertyValue);
            }

            return entityRecord;
        }
Exemplo n.º 29
0
        public IEnumerable<string> UploadToTempDir(HttpFileCollectionBase files)
        {
            var fileNames = new List<string>();

            if (files.Count > 0)
            {
                foreach (string file in files)
                {
                    var postedFile = files[file];
                    string uniqueName = GenerateUniqueName(postedFile.FileName);
                    var filePath = Path.Combine(ServerTools.Paths.TempFolder, uniqueName);
                    postedFile.SaveAs(filePath);
                    fileNames.Add(uniqueName);
                    // NOTE: To store in memory use postedFile.InputStream
                }
            }
            return fileNames;
        }
Exemplo n.º 30
0
        public void Upload(HttpFileCollectionBase files, string folderPath, string fileSuffix)
        {
            bool exists = Directory.Exists(folderPath);

            if (!exists)
                Directory.CreateDirectory(folderPath);

            for (int i = 0; i < files.Count; i++)
            {
                var file = files[i];

                var fileName = GetFileNameWithSuffix(Path.GetFileName(file.FileName), fileSuffix);

                //Create Thumbnail
                CreateThumnail(file, folderPath, fileSuffix);
                //var path = Path.Combine(folderPath, fileName);
                file.SaveAs(Path.Combine(folderPath, fileName));
            }
        }
Exemplo n.º 31
0
        JsonResult IDriver.Upload(string target, System.Web.HttpFileCollectionBase targets, bool addWithNewIndex)
        {
            string     dest  = this.DecodeTarget(this.GetCorectTarget(target));
            WebDavRoot lroot = this.GetRoot(target);

            if (lroot.Directory.DisplayName == Recived)
            {
                dest  = Upload + "/";
                lroot = this.roots.FirstOrDefault(x => x.Directory.DisplayName == Upload);
            }
            AddResponse response  = new AddResponse();
            DirInfo     destInfo  = client.GetInfo(dest);
            JsonResult  errorResp = Error.Message("Connector.WebDavDriver: Ошибка сервиса. Невозможно загрузить файл. Некорректное имя файла!");

            for (int i = 0; i < targets.AllKeys.Length; i++)
            {
                HttpPostedFileBase file = targets[i];
                if (file == null)
                {
                    return(errorResp);
                }
                string name = file.FileName;

                if (file.FileName.Contains("#"))
                {
                    name = file.FileName.Replace("#", "");
                }
                if (addWithNewIndex)
                {
                    name = GetCorrectDestinationFileName(destInfo.RelPath + name);
                }
                client.Upload(dest + Path.GetFileName(name), file.InputStream);
                DirInfo fileInfo = client.GetInfo(dest + Path.GetFileName(name));
                if (fileInfo == null)
                {
                    return(errorResp);
                }
                response.Added.Add((FileDTO)DTOBase.Create(fileInfo, destInfo, lroot));
            }

            return(Json(response));
        }
Exemplo n.º 32
0
        private static PropertyValue GetPropertyValueForFile(
            Property property,
            IValueProvider valueProvider,
            HttpFileCollectionBase files)
        {
            var propertyValue = new PropertyValue(property);

            var file = files[property.Name];
            propertyValue.Raw = file;
            if (property.TypeInfo.IsFileStoredInDb == false &&
                property.FileOptions.NameCreation == NameCreation.UserInput)
            {
                var providedName = (string)valueProvider.GetValue(property.Name)
                    .ConvertTo(typeof(string), CultureInfo.CurrentCulture);
                propertyValue.Additional = providedName;
            }
            var isDeleted = false;

            if (file == null || file.ContentLength > 0)
            {
                isDeleted = false;
            }
            else
            {
                var isDeletedKey = property.Name + "_delete";
                if (valueProvider.ContainsPrefix(isDeletedKey))
                {
                    isDeleted =
                       ((bool?)
                           valueProvider.GetValue(isDeletedKey)
                               .ConvertTo(typeof(bool), CultureInfo.CurrentCulture)).GetValueOrDefault();
                }
            }

            if (isDeleted)
            {
                propertyValue.DataBehavior = DataBehavior.Clear;
                propertyValue.Additional = null;
            }

            return propertyValue;
        }
Exemplo n.º 33
0
        static IDictionary<string, IEnumerable<HttpPostedFileBase>> GetFiles(HttpFileCollectionBase files)
        {
            var source = new List<KeyValuePair<string, HttpPostedFileBase>>();

            for (var i = 0; i < files.Count; i++)
            {
                var key = files.AllKeys[i];
                if (key == null)
                    continue;

                var file = GetFile(files[i]);
                if(file != null)
                    source.Add(new KeyValuePair<string, HttpPostedFileBase>(key, file));
            }

            var groupedFiles = source.GroupBy(kvp => kvp.Key, kvp => kvp.Value, StringComparer.OrdinalIgnoreCase);

            var dictionary = groupedFiles.ToDictionary(x => x.Key, x => x.ToArray().AsEnumerable());

            return dictionary;
        }
Exemplo n.º 34
0
        /// <summary> </summary>
        JsonResult IDriver.Upload(string target, System.Web.HttpFileCollectionBase targets)
        {
            FullPath dest     = ParsePath(target);
            var      response = new AddResponse();

            for (int i = 0; i < targets.AllKeys.Length; i++)
            {
                HttpPostedFileBase file = targets[i];
                string             path = Path.Combine(dest.Directory.FullName, file.FileName);
                if (File.Exists(path))
                {
                    //TODO: throw error
                }
                else
                {
                    file.SaveAs(path);
                    response.added.Add((FileDTO)DTOBase.Create(new FileInfo(path), dest.Root));
                }
            }
            return(Json(response));
        }
Exemplo n.º 35
0
        public static string SaveFile(HttpFileCollectionBase Files, string path)
        {
            try
            {
                if (Files.Count > 0)
                {
                    var file = Files[0];

                    if (file != null && file.ContentLength > 0)
                    {
                        var fileName = Path.GetFileName(file.FileName);
                        path = Path.Combine(path, fileName);
                        file.SaveAs(path);
                    }
                }
                return path;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Exemplo n.º 36
0
        public void SubmitForm(OFormPart form, Dictionary<string, string> postData, HttpFileCollectionBase files, string ipSubmiter)
        {
            if (form == null)
                throw new ArgumentNullException("form");
            if (postData == null)
                throw new ArgumentNullException("postData");

            var formResult = SaveFormToDB(form, postData, files, ipSubmiter);
            postData.Add("oforms.formResult.Id", formResult.Id.ToString());

            if (form.SendEmail) {
                _messageManager.Send(form.Record.ContentItemRecord,
                    MessageTypes.SendFormResult,
                    "email",
                    postData);
            }

            if (!form.SaveResultsToDB)
            {
                _resultRepo.Delete(formResult);
            }
        }
        public IList<ProductImage> UploadFiles(HttpFileCollectionBase files)
        {
            IList<ProductImage> result = new List<ProductImage>();

            foreach (string key in files.Keys)
            {
                var file = files[key];

                byte[] photoBytes = new byte[file.ContentLength];
                file.InputStream.Read(photoBytes, 0, file.ContentLength);
                var thumbnailSize = new Size(200, 0);

                ProductImage image = new ProductImage();

                image.Url = this.SaveLargeImage(photoBytes, file.FileName);
                image.Thumbnail = this.SaveThumbnail(photoBytes, file.FileName);

                result.Add(image);
            }

            return result;
        }
Exemplo n.º 38
0
        public void UploadImage(System.Web.HttpFileCollectionBase files, Racoonogram.Models.Image i)
        {
            string fullPath = GetServerPath("~/Content/Content-image/");

            foreach (string file in files)
            {
                var upload = files[file];
                if (upload != null)
                {
                    System.Drawing.Image  waterMarkIm;
                    System.Drawing.Bitmap bit;
                    try
                    {
                        //get filename
                        string fileName = System.IO.Path.GetFileName(upload.FileName);
                        //save file
                        string fullPathName = GetServerPath("~/Content/MidTerm/") + fileName;
                        upload.SaveAs(fullPathName);
                        new ImageService().AddImage(i);
                        string newName = fullPath + i.ImageId + ".jpg";
                        if (System.IO.File.Exists(newName))
                        {
                            System.IO.File.Delete(newName);
                        }

                        System.Drawing.Image imNormal = System.Drawing.Image.FromFile(fullPathName);
                        imNormal.Save(newName);

                        imNormal = new ImageHandler().ResizeImage(imNormal, 1920, 1920);

                        /*ДОБАВЛЕНИЕ ВОДЯНОГО ЗНАКА*/
                        if (imNormal.Width > imNormal.Height)
                        {
                            waterMarkIm = System.Drawing.Image.FromFile(GetServerPath("~/Content/Images/") + "Watermark_.png");
                        }
                        else if (imNormal.Width < imNormal.Height)
                        {
                            waterMarkIm = System.Drawing.Image.FromFile(GetServerPath("~/Content/Images/") + "Watermark__.png");
                        }
                        else
                        {
                            waterMarkIm = System.Drawing.Image.FromFile(GetServerPath("~/Content/Images/") + "Watermark___.png");
                        }
                        int h = imNormal.Height;
                        int w = imNormal.Width;
                        bit = new Bitmap(w, h);
                        using (Graphics g = Graphics.FromImage(bit))
                        {
                            g.DrawImage(imNormal, 0, 0, w, h);
                            g.DrawImage(waterMarkIm, 10, ((imNormal.Height - waterMarkIm.Height) / 2), waterMarkIm.Width, waterMarkIm.Height);
                        }

                        bit.Save(fullPath + i.ImageId + "_normal.jpg");

                        System.Drawing.Image imNormalSmall = new ImageHandler().ResizeImage(bit, 400, 240);
                        imNormalSmall.Save(fullPath + i.ImageId + "_sm.jpg");

                        imNormalSmall = new ImageHandler().ResizeImage(imNormalSmall, 200, 40);
                        imNormalSmall.Save(fullPath + i.ImageId + "_xs.jpg");
                        imNormal = null;
                        System.IO.File.Delete(fullPathName);
                    }
                    catch (Exception ex)
                    {
                        string exeption = ex.Message;
                    }
                }
            }
        }
Exemplo n.º 39
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="httpFiles"></param>
        /// <param name="codeCol">条码列</param>
        /// <param name="countCol">实盘列</param>
        /// <param name="minRow">起始行</param>
        /// <param name="maxRow">截止行</param>
        /// <returns></returns>
        public static OpResult Import(TreasuryLocks obj, System.Web.HttpFileCollectionBase httpFiles, char codeCol, char countCol, int minRow, int maxRow, string checkUID)
        {
            var op = new OpResult();

            try
            {
                if (httpFiles.Count <= 0 || httpFiles[0].ContentLength <= 0)
                {
                    op.Message = "请先选择Excel文件";
                    return(op);
                }
                var stream = httpFiles[0].InputStream;
                var ext    = httpFiles[0].FileName.Substring(httpFiles[0].FileName.LastIndexOf("."));
                if (!(ext.Equals(".xls", StringComparison.CurrentCultureIgnoreCase) ||
                      ext.Equals(".xlsx", StringComparison.CurrentCultureIgnoreCase)))
                {
                    op.Message = "请先选择Excel文件";
                    return(op);
                }
                var over     = HttpContext.Current.Request["over"].ToType <short?>();
                int?checkCol = null;
                if (!HttpContext.Current.Request["CheckCol"].IsNullOrEmpty())
                {
                    checkCol = (int)Convert.ToChar(HttpContext.Current.Request["CheckCol"]);
                }
                obj.CompanyId = CommonService.CompanyId;
                var dt       = new ExportExcel().ToDataTable(stream, minRow: minRow, maxRow: maxRow);
                var codeIdx  = Convert.ToInt32(codeCol) - 65;
                var countIdx = Convert.ToInt32(countCol) - 65;
                var users    = new List <Sys.Entity.SysUserInfo>();
                if (checkCol.HasValue)
                {
                    var codes = dt.AsEnumerable().Select(o => o[checkCol.Value - 65].ToString()).Distinct().ToList();
                    users = UserInfoService.FindList(o => o.CompanyId == CommonService.CompanyId && codes.Contains(o.UserCode));
                }
                var stocks = new List <StockTakingLog>();
                var errLs  = new Dictionary <int, string>();
                int idx    = 1;
                foreach (DataRow dr in dt.Rows)
                {
                    idx++;
                    string barcode = "", number = "";
                    try
                    {
                        barcode = dr[codeIdx].ToString();
                        number  = dr[countIdx].ToString();
                        if (checkCol.HasValue)
                        {
                            var code = dr[checkCol.Value - 65].ToString();
                            if (!code.IsNullOrEmpty())
                            {
                                var user = users.FirstOrDefault(o => o.UserCode == code);
                                if (user != null)
                                {
                                    checkUID = user.UID;
                                }
                                else
                                {
                                    errLs.Add(idx, barcode + "&nbsp;&nbsp;盘点员工号不存在!");
                                    continue;
                                }
                            }
                        }
                    }
                    catch (Exception)
                    {
                        throw new Exception("列选择超过范围!");
                    }
                    if (barcode.IsNullOrEmpty())
                    {
                        continue;
                    }
                    if (number.IsNullOrEmpty() && !barcode.IsNullOrEmpty())
                    {
                        errLs.Add(idx, barcode + "&nbsp;&nbsp;实盘数量为空");
                        continue;
                    }
                    decimal num = 0;
                    if (!decimal.TryParse(number, out num) || num < 0)
                    {
                        errLs.Add(idx, barcode + "&nbsp;&nbsp;实盘数量小于零");
                        continue;
                    }

                    var st = stocks.FirstOrDefault(o => o.Barcode == barcode);
                    if (st != null)
                    {
                        st.Number += num;
                    }
                    else
                    {
                        stocks.Add(new StockTakingLog()
                        {
                            Id         = idx,
                            Barcode    = barcode,
                            Number     = num,
                            CheckBatch = obj.CheckBatch,
                            CheckUID   = checkUID,
                            CreateDT   = DateTime.Now,
                            State      = over.GetValueOrDefault(),
                            SysPrice   = 0,
                            CompanyId  = obj.CompanyId,
                            Source     = 3
                        });
                    }
                }
                op = SaveOrUpdate(obj, "[]", stocks.ToJson(), "[]", HttpContext.Current.Request["ActualDate"], 1);
                var errs = op.Data as Dictionary <int, string>;
                if (errs == null)
                {
                    errs = new Dictionary <int, string>();
                }
                foreach (var de in errs)
                {
                    errLs.Add(de.Key, de.Value);
                }
                if (errLs.Any())
                {
                    var html = "<ul><li>成功导入{0}条数据,余{1}条导入失败!</li><li><a href=\"javascript:void(0)\" onclick=\"viewErr()\">查看失败记录!</a></li></ul>";
                    op.Message  = string.Format(html, stocks.Count - errs.Count, errLs.Count);
                    op.Descript = "<dl><dt>以下数据导入失败:</dt>{0}</dl>";
                    string str = "";
                    foreach (var de in errLs)
                    {
                        str += "<dd>行" + de.Key + ":" + de.Value + "</dd>";
                    }
                    op.Descript = string.Format(op.Descript, str);
                }
                else
                {
                    op.Message = "<ul><li>成功导入" + stocks.Count + "条数据!</li></ul>";
                }
                op.Message  = System.Web.HttpUtility.UrlEncode(op.Message);
                op.Descript = System.Web.HttpUtility.UrlEncode(op.Descript);
                Log.WriteInsert("盘点导入", Sys.LogModule.库存管理);
            }
            catch (Exception ex)
            {
                op.Message = ex.Message;
                Log.WriteError(ex);
            }
            return(op);
        }
Exemplo n.º 40
0
        JsonResult IDriver.Upload(string target, System.Web.HttpFileCollectionBase targets)
        {
            FullPath dest     = ParsePath(target);
            var      response = new AddResponse();

            if (dest.Root.MaxUploadSize.HasValue)
            {
                for (int i = 0; i < targets.AllKeys.Length; i++)
                {
                    HttpPostedFileBase file = targets[i];
                    if (file.ContentLength > dest.Root.MaxUploadSize.Value)
                    {
                        return(Error.MaxUploadFileSize());
                    }
                }
            }
            for (int i = 0; i < targets.AllKeys.Length; i++)
            {
                HttpPostedFileBase file = targets[i];
                string             path = Path.Combine(dest.Directory.FullName, file.FileName);

                if (File.Exists(path))
                {
                    if (dest.Root.UploadOverwrite)
                    {
                        //if file already exist we rename the current file,
                        //and if upload is succesfully delete temp file, in otherwise we restore old file
                        string tmpPath  = path + Guid.NewGuid();
                        bool   uploaded = false;
                        try
                        {
                            File.Move(path, tmpPath);
                            file.SaveAs(path);
                            uploaded = true;
                        }
                        catch { }
                        finally
                        {
                            if (uploaded)
                            {
                                File.Delete(tmpPath);
                            }
                            else
                            {
                                if (File.Exists(path))
                                {
                                    File.Delete(path);
                                }
                                File.Move(tmpPath, path);
                            }
                        }
                    }
                    else
                    {
                        string name = null;
                        for (int j = 1; j < 100; j++)
                        {
                            string suggestName = Path.GetFileNameWithoutExtension(file.FileName) + "-" + j + Path.GetExtension(file.FileName);
                            if (!File.Exists(Path.Combine(dest.Directory.FullName, suggestName)))
                            {
                                name = suggestName;
                                break;
                            }
                        }
                        if (name == null)
                        {
                            name = Path.GetFileNameWithoutExtension(file.FileName) + "-" + Guid.NewGuid() + Path.GetExtension(file.FileName);
                        }
                        path = Path.Combine(dest.Directory.FullName, name);
                        file.SaveAs(path);
                    }
                }
                else
                {
                    file.SaveAs(path);
                }
                response.Added.Add((FileDTO)DTOBase.Create(new FileInfo(path), dest.Root));
            }
            return(Json(response));
        }
Exemplo n.º 41
0
        JsonResult IDriver.Upload(string target, System.Web.HttpFileCollectionBase targets)
        {
            FullPath dest     = ParsePath(target);
            var      response = new AddResponse();

            if (dest.Root.MaxUploadSize.HasValue)
            {
                for (int i = 0; i < targets.AllKeys.Length; i++)
                {
                    HttpPostedFileBase file = targets[i];
                    if (file.ContentLength > dest.Root.MaxUploadSize.Value)
                    {
                        return(Error.MaxUploadFileSize());
                    }
                }
            }
            for (int i = 0; i < targets.AllKeys.Length; i++)
            {
                HttpPostedFileBase file = targets[i];
                FileInfo           path = new FileInfo(Path.Combine(dest.Directory.FullName, Path.GetFileName(file.FileName)));

                if (path.Exists)
                {
                    if (dest.Root.UploadOverwrite)
                    {
                        //if file already exist we rename the current file,
                        //and if upload is succesfully delete temp file, in otherwise we restore old file
                        string tmpPath  = path.FullName + Guid.NewGuid();
                        bool   uploaded = false;
                        try
                        {
                            file.SaveAs(tmpPath);
                            uploaded = true;
                        }
                        catch { }
                        finally
                        {
                            if (uploaded)
                            {
                                File.Delete(path.FullName);
                                File.Move(tmpPath, path.FullName);
                            }
                            else
                            {
                                File.Delete(tmpPath);
                            }
                        }
                    }
                    else
                    {
                        file.SaveAs(Path.Combine(path.DirectoryName, Helper.GetDuplicatedName(path)));
                    }
                }
                else
                {
                    file.SaveAs(path.FullName);
                }
                response.Added.Add((FileDTO)DTOBase.Create(new FileInfo(path.FullName), dest.Root));
            }
            return(Json(response));
        }
Exemplo n.º 42
0
        public JsonResult SaveSlideShow(SlideShowViewModel model)
        {
            return(ExecuteFunctionRun(() =>
            {
                System.Web.HttpFileCollectionBase files = HttpContext.Request.Files;
                var parentNode = this.Engine.FunctionAclManager.GetFunctionNodeByCode(model.ParentCode);
                ActionResult result = SlideShowValidate(model);
                // 检查文件大小
                if (files.Count > 0 && files[0].ContentLength > 1024 * 1024)
                {
                    result.Success = false;
                    result.Message = "msgGlobalString.ImageMaxLength";
                    return Json(result, "text/html");
                }
                else if (null == parentNode)
                {
                    result.Message = "HybridApp.ParentNodeNotExist";
                    result.Success = false;
                    return Json(result, "text/html");
                }
                else if (result.Success == false)
                {
                    return Json(result, JsonRequestBehavior.AllowGet);
                }

                SlideShow slideShow;
                //新建
                if (string.IsNullOrEmpty(model.ObjectID))
                {
                    string guid = Guid.NewGuid().ToString();
                    this.SaveImage(files, guid, parentNode.Code);
                    slideShow = new SlideShow()
                    {
                        SlideCode = model.Code,
                        SortKey = model.SortKey,
                        IsDisplay = model.IsDisplay,
                        Description = model.Description,
                        Url = model.Url,
                        ObjectID = guid,
                        ParentCode = model.ParentCode,
                    };

                    if (!this.Engine.HybridAppManager.AddSlideShow(slideShow))
                    {
                        result.Success = false;
                        result.Message = "msgGlobalString.SaveFailed";
                    }
                }
                else
                {
                    //编辑
                    slideShow = this.Engine.HybridAppManager.GetSlideShow(model.Code);
                    slideShow.IsDisplay = model.IsDisplay;
                    slideShow.SortKey = model.SortKey;
                    slideShow.Url = model.Url;
                    slideShow.Description = model.Description;
                    if (this.Engine.HybridAppManager.UpdateSlideShow(slideShow))
                    {
                        this.SaveImage(files, slideShow.ObjectID, parentNode.ObjectID);
                    }
                    else
                    {
                        result.Success = false;
                        result.Message = "msgGlobalString.SaveFailed";
                    }
                }

                return Json(result, "text/html", JsonRequestBehavior.AllowGet);
            }));
        }
        public DataTable ImportFile()
        {
            System.Web.HttpFileCollectionBase files = HttpContext.Request.Files; files = Request.Files;
            if (files == null || files.Count == 0)
            {
                return(null);
            }
            string        attachmentId       = Guid.NewGuid().ToString();
            DataTable     data               = new DataTable();
            List <string> participantColunms = new List <string>();

            for (int i = 0; i < files.Count; i++)
            {
                HttpPostedFileBase file = files[i] as System.Web.HttpPostedFileBase;
                if (file.ContentLength == 0)
                {
                    continue;
                }

                string    sheetName        = "sheet1";
                bool      isFirstRowColumn = true;
                IWorkbook workbook         = null;
                ISheet    sheet            = null;
                int       startRow         = 0;
                try
                {
                    workbook = WorkbookFactory.Create(file.InputStream);

                    if (sheetName != null)
                    {
                        sheet = workbook.GetSheet(sheetName);
                    }
                    else
                    {
                        sheet = workbook.GetSheetAt(0);
                    }
                    if (sheet != null)
                    {
                        IRow firstRow  = sheet.GetRow(0);
                        int  cellCount = firstRow.LastCellNum; //一行最后一个cell的编号 即总的列数

                        if (isFirstRowColumn)
                        {
                            for (int j = firstRow.FirstCellNum; j < cellCount; ++j)
                            {
                                if (firstRow.GetCell(j).StringCellValue.Contains("名称$"))
                                {
                                    participantColunms.Add(firstRow.GetCell(j).StringCellValue);
                                }
                                DataColumn column = new DataColumn(firstRow.GetCell(j).StringCellValue);
                                data.Columns.Add(column);
                            }
                            startRow = sheet.FirstRowNum + 1;
                        }
                        else
                        {
                            startRow = sheet.FirstRowNum;
                        }

                        //最后一列的标号
                        int rowCount = sheet.LastRowNum;
                        for (int j = startRow; j <= rowCount; ++j)
                        {
                            IRow row = sheet.GetRow(j);
                            if (row == null)
                            {
                                continue;              //没有数据的行默认是null       
                            }
                            DataRow dataRow = data.NewRow();
                            for (int k = row.FirstCellNum; k < cellCount; ++k)
                            {
                                if (row.GetCell(k) != null) //同理,没有数据的单元格都默认是null
                                {
                                    dataRow[k] = row.GetCell(k).ToString();
                                }
                            }
                            data.Rows.Add(dataRow);
                        }
                    }
                }
                catch
                {
                }
                finally
                {
                    // stream.Close();
                }
            }

            return(data);
        }
Exemplo n.º 44
0
        /// <summary>
        ///更新用户信息
        /// </summary>
        /// <param name="unit"></param>
        /// <returns></returns>
        public JsonResult UpdateUserInfo(string UserID, string Mobile, string OfficePhone, string Email, string FacsimileTelephoneNumber, bool chkEmail, bool chkApp, bool chkWeChat, bool chkMobileMessage, bool chkDingTalk)
        {
            return(this.ExecuteFunctionRun(() =>
            {
                ActionResult result = new ActionResult(true);

                #region add by chenghuashan 2018-02-24
                if (!string.IsNullOrEmpty(Mobile))
                {
                    string sql = "SELECT Code,Name FROM OT_User WHERE Mobile='" + Mobile + "' and ObjectID <>'" + UserID + "'";
                    System.Data.DataTable dt = this.Engine.EngineConfig.CommandFactory.CreateCommand().ExecuteDataTable(sql);
                    if (dt.Rows.Count > 0)
                    {
                        string msg = "";
                        foreach (System.Data.DataRow row in dt.Rows)
                        {
                            msg += "\n" + row["Name"] + "(" + row["Code"] + ")";
                        }
                        result.Success = false;
                        result.Message = "手机号码不允许重复,以下用户使用此手机号" + msg;
                        return Json(result, "text/html");
                    }
                }
                #endregion

                //UserID修改人的ID
                Organization.User EditUnit = (OThinker.Organization.User)Engine.Organization.GetUnit(UserID);
                string dirPath = AppDomain.CurrentDomain.BaseDirectory + "TempImages//face//" + Engine.EngineConfig.Code + "//" + this.UserValidator.User.ParentID + "//";
                string ID = this.UserValidator.UserID;

                System.Web.HttpFileCollectionBase files = HttpContext.Request.Files;

                if (files.Count > 0)
                {
                    byte[] content = GetBytesFromStream(files[0].InputStream);
                    if (content.Length > 0)
                    {
                        string Type = files[0].ContentType;
                        string fileExt = ".jpg";
                        string savepath = dirPath + ID + fileExt;
                        try
                        {
                            if (!Directory.Exists(Path.GetDirectoryName(savepath)))
                            {
                                Directory.CreateDirectory(Path.GetDirectoryName(savepath));
                            }
                            using (FileStream fs = new FileStream(savepath, FileMode.OpenOrCreate, FileAccess.ReadWrite))
                            {
                                using (BinaryWriter bw = new BinaryWriter(fs))
                                {
                                    bw.Write(content);
                                    bw.Close();
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            // 这里如果直接输出异常,那么用户不能登录
                            Engine.LogWriter.Write("加载用户图片出现异常,UserValidator:" + ex.ToString());
                        }

                        if (UserID == this.UserValidator.UserID)
                        {
                            this.UserValidator.ImagePath = ID + fileExt;
                        }
                        FileInfo file = GetFile(dirPath, ID + fileExt);
                        if (file != null)
                        {
                            AttachmentHeader header = this.Engine.BizObjectManager.GetAttachmentHeader(OThinker.Organization.User.TableName, this.UserValidator.UserID, this.UserValidator.UserID);
                            if (header != null)
                            {
                                Engine.BizObjectManager.UpdateAttachment(header.BizObjectSchemaCode,
                                                                         header.BizObjectId,
                                                                         header.AttachmentID, this.UserValidator.UserID, file.Name, Type, content, header.FileFlag);
                            }
                            else
                            {
                                // 用户头像采用附件上传方式
                                Attachment attach = new Attachment()
                                {
                                    ObjectID = this.UserValidator.UserID,
                                    BizObjectId = this.UserValidator.UserID,
                                    BizObjectSchemaCode = OThinker.Organization.User.TableName,
                                    FileName = file.Name,
                                    Content = content,
                                    ContentType = Type,
                                    ContentLength = (int)file.Length
                                };
                                Engine.BizObjectManager.AddAttachment(attach);
                            }
                            // 用户头像
                            EditUnit.ImageID = UserID;
                            EditUnit.ImageUrl = "TempImages//face//" + Engine.EngineConfig.Code + "//" + this.UserValidator.User.ParentID + "//" + file.Name;
                            result.Extend = new
                            {
                                ImageUrl = EditUnit.ImageUrl
                            };
                        }
                    }
                }

                EditUnit.Mobile = Mobile;
                EditUnit.OfficePhone = OfficePhone;
                EditUnit.Email = Email;
                EditUnit.FacsimileTelephoneNumber = FacsimileTelephoneNumber;
                EditUnit.ModifiedTime = DateTime.Now;

                //接收消息
                EditUnit.SetNotifyType(Organization.NotifyType.App, chkApp);
                EditUnit.SetNotifyType(Organization.NotifyType.Email, chkEmail);
                EditUnit.SetNotifyType(Organization.NotifyType.MobileMessage, chkMobileMessage);
                EditUnit.SetNotifyType(Organization.NotifyType.WeChat, chkWeChat);
                EditUnit.SetNotifyType(Organization.NotifyType.DingTalk, chkDingTalk);

                // 写入服务器
                Organization.HandleResult HandleResult = Engine.Organization.UpdateUnit(this.UserValidator.UserID, EditUnit);
                if (HandleResult == Organization.HandleResult.SUCCESS && EditUnit.ObjectID == this.UserValidator.UserID)
                {
                    this.UserValidator.User = EditUnit as OThinker.Organization.User;
                }
                else
                {
                    result.Success = false;
                    result.Extend = null;
                }
                return Json(result, "text/html", JsonRequestBehavior.AllowGet);
            }, string.Empty));
        }
Exemplo n.º 45
0
        JsonResult IDriver.Upload(string target, System.Web.HttpFileCollectionBase targets)
        {
            var dest     = ParsePath(target);
            var response = new AddResponse();

            if (dest.Root.MaxUploadSize.HasValue)
            {
                for (int i = 0; i < targets.AllKeys.Length; i++)
                {
                    HttpPostedFileBase file = targets[i];
                    if (file.ContentLength > dest.Root.MaxUploadSize.Value)
                    {
                        return(Error.MaxUploadFileSize());
                    }
                }
            }
            for (int i = 0; i < targets.AllKeys.Length; i++)
            {
                var file    = targets[i];
                var newFile = new ResourceFile {
                    Name            = file.FileName,
                    Parent          = dest.Directory,
                    Owner           = dest.Directory.Owner,
                    ResourceId      = Guid.NewGuid(),
                    Private         = dest.Directory.Private,
                    TypesOfResource = dest.Directory.TypesOfResource,
                    Project         = dest.Directory.Project,
                    MimeType        = Helper.GetMimeType(file.FileName)
                };
                using (var blob = BlobFactory.GetBlobStorage(newFile.ResourceId, BlobFactory.Container.Resources)) {
                    if (dest.Root.UploadOverwrite)
                    {
                        //if file already exist we rename the current file,
                        //and if upload is succesfully delete temp file, in otherwise we restore old file
                        var uploaded = false;
                        try {
                            var bytes = new byte[file.InputStream.Length];
                            file.InputStream.Seek(0, SeekOrigin.Begin);
                            file.InputStream.Read(bytes, 0, bytes.Length);
                            blob.Content = bytes;
                            blob.Save();
                            uploaded = true;
                        } catch {
                        } finally {
                            if (!uploaded)
                            {
                                blob.Remove();
                            }
                        }
                    }
                    else
                    {
                        throw new NotImplementedException("");
                    }
                    ResourceManager.Instance.AddResource(newFile);
                    response.Added.Add((FileDTO)DTOBase.Create(newFile, dest.Root));
                }
            }
            if (!HttpContext.Current.Request.AcceptTypes.Contains("application/json"))
            {
                return(Json(response, "text/html"));
            }
            else
            {
                return(Json(response));
            }
        }
        public JsonResult ImportFile()
        {
            System.Web.HttpFileCollectionBase files = HttpContext.Request.Files; files = Request.Files;
            if (files == null || files.Count == 0)
            {
                return(null);
            }
            string    attachmentId = Guid.NewGuid().ToString();
            DataTable data         = new DataTable();

            for (int i = 0; i < files.Count; i++)
            {
                HttpPostedFileBase file = files[i] as System.Web.HttpPostedFileBase;
                if (file.ContentLength == 0)
                {
                    continue;
                }
                string    sheetName        = "sheet1";
                bool      isFirstRowColumn = true;
                IWorkbook workbook         = null;
                ISheet    sheet            = null;
                int       startRow         = 0;
                try
                {
                    workbook = WorkbookFactory.Create(file.InputStream);

                    if (sheetName != null)
                    {
                        sheet = workbook.GetSheet(sheetName);
                    }
                    else
                    {
                        sheet = workbook.GetSheetAt(0);
                    }
                    if (sheet != null)
                    {
                        IRow firstRow  = sheet.GetRow(0);
                        int  cellCount = firstRow.LastCellNum; //一行最后一个cell的编号 即总的列数
                        if (isFirstRowColumn)
                        {
                            for (int j = firstRow.FirstCellNum; j < cellCount; ++j)
                            {
                                DataColumn column = new DataColumn(firstRow.GetCell(j).StringCellValue);
                                data.Columns.Add(column);
                            }
                            startRow = sheet.FirstRowNum + 1;
                        }
                        else
                        {
                            startRow = sheet.FirstRowNum;
                        }
                        //最后一列的标号
                        int rowCount = sheet.LastRowNum;
                        for (int j = startRow; j <= rowCount; ++j)
                        {
                            IRow row = sheet.GetRow(j);
                            if (row == null)
                            {
                                continue;              //没有数据的行默认是null       
                            }
                            DataRow dataRow = data.NewRow();
                            for (int k = row.FirstCellNum; k < cellCount; ++k)
                            {
                                if (row.GetCell(k) != null) //同理,没有数据的单元格都默认是null
                                {
                                    dataRow[k] = row.GetCell(k).ToString();
                                }
                            }
                            data.Rows.Add(dataRow);
                        }
                    }
                }
                catch
                { }
                finally
                {
                    // stream.Close();
                }
            }
            if (data.Rows.Count > 0)
            {
                string[] list = new string[data.Rows.Count];
                for (int i = 0; i < data.Rows.Count; i++)
                {
                    string row = string.Empty;
                    for (int y = 0; y < data.Rows[i].ItemArray.Length; y++)
                    {
                        row += data.Rows[i].ItemArray[y] + ",";
                    }
                    row     = row.TrimEnd(',');
                    list[i] = row;
                }
                return(Json(list, "text/html", JsonRequestBehavior.AllowGet));
            }
            return(Json(new string[0], JsonRequestBehavior.AllowGet));
        }