Beispiel #1
0
    protected void btnUpload_Click(object sender, EventArgs e)
    {
        string filename = Path.GetFileName(fileUpload1.PostedFile.FileName);

        string GetExts = Path.GetExtension(filename);

        Stream str = fileUpload1.PostedFile.InputStream;
        BinaryReader br = new BinaryReader(str);
        Byte[] size = br.ReadBytes((int)str.Length);

        using (ROPAEntities obj = new ROPAEntities())
        {
            UploadFile upld = new UploadFile();

            upld.GUID = Guid.NewGuid().ToString();
            //upld.FIleFor=100;
            upld.FIleFor = filename;
            upld.SurApp_Id = 47;
            upld.fileext = GetExts;

            obj.AddToUploadFiles(upld);
            obj.SaveChanges();
        }
        BindGridviewData();
    }
Beispiel #2
0
    protected void btnUpload_Click(object sender, EventArgs e)
    {
        try
        {
            var filename = Path.GetFileName(fileUpload1.PostedFile.FileName);

            var getExts = Path.GetExtension(filename);

            var str = fileUpload1.PostedFile.InputStream;
            var br = new BinaryReader(str);
            var size = br.ReadBytes((int) str.Length);

            using (var obj = new ROPAEntities())
            {
                var upld = new UploadFile();
                upld.GUID = Guid.NewGuid().ToString();
                upld.AppVersion = (decimal) 2.30;

                upld.FIleFor = filename;
                upld.SurApp_Id = 47;
                upld.fileext = getExts;

                obj.AddToUploadFiles(upld);
                obj.SaveChanges();
            }
            BindGridviewData();
        }
        catch (Exception)
        {

        }
    }
        private int DoPost(NameValueCollection form, string body, int[] users = null, string filename = null, string fileContentType = null, byte[] filedata = null)
        {
            var files = new UploadFile[0];
            if (!string.IsNullOrEmpty(filename) && null != filedata)
            {
                var ms = new MemoryStream(filedata);
                files = new[] { new UploadFile(ms, "attachment1", filename, fileContentType) };
            }

            form["body"] = body;
            if (null != users)
            {
                form["cc"] = string.Join(",", users.Select(i => string.Format("[[user:{0}]]", i)));
            }

            var req = (HttpWebRequest)WebRequest.Create("https://www.yammer.com/api/v1/messages.json");
            req.Headers.Add("Authorization", "Bearer " + _authCode);
            HttpWebResponse resp = HttpUploadHelper.Upload(req, files, form);

            using (Stream s = resp.GetResponseStream())
            using (StreamReader sr = new StreamReader(s))
            {
                var data = sr.ReadToEnd();
                var obj = JsonConvert.DeserializeObject<JObject>(data);
                return (int)obj["messages"][0]["id"];
            }
        }
    protected void btnUpload_Click(object sender, EventArgs e)
    {
        string filename = Path.GetFileName(fileUpload1.PostedFile.FileName);

        Stream stream = fileUpload1.PostedFile.InputStream;

        string extension = Path.GetExtension(filename);
        //Write Save Logic  to file/
        BinaryReader br = new BinaryReader(stream);
        Byte[] size = br.ReadBytes((int)stream.Length);
        //SaveToFolder(stream, filename);

        //Database already here
        List<UploadFile> L = ResolveList();
        using (ROPAEntities obj = new ROPAEntities())
        {
            Guid G = Guid.NewGuid();
            UploadFile upld = new UploadFile();
            upld.GUID = G.ToString();
            upld.FIleFor = filename;
            upld.SurApp_Id = null;
            obj.AddToUploadFiles(upld);
            obj.SaveChanges();

            L.Add(upld);
        }
        UpdateSession(L);
        BindGridviewData();
    }
 public bool Replace(string fileKey,string fileName, string contentType, Stream data)
 {
     var uploadFile = new UploadFile(data, null, fileName, contentType);
     var response = _client.Replace(fileKey, uploadFile);
     var result = CommandResult.Create(response);
     return result.StatusCode == StatusCodes.Success;
 }
Beispiel #6
0
 protected void btnUp_Click(object sender, EventArgs e)
 {
     lblTip.Text = "";
     try
     {
         string fileName = fileup.FileName;
         string ext = Path.GetExtension(fileName).ToLower(); // 扩展名判断
         if (ext == ".asp" || ext == ".aspx" || ext == ".js" || ext == ".html")
         {
             lblTip.Text = "非法文件格式 !";
             return;
         }
         string SavaFolder = Server.MapPath("../VXer_upload_file/");
         string filepath = SavaFolder + fileName;
         if (File.Exists(filepath))
         {   // 若服务器存在同名文件则将文件名改为系统当前时间
             fileName = DateTime.Now.ToString() + ext;
             fileName = fileName.Replace(':', '_');
             filepath = SavaFolder + fileName;
         }
         fileup.SaveAs(filepath);
         UploadFile UpFile = new UploadFile();
         UpFile.FileName = txtFileName.Text.Trim();
         UpFile.TypeId = int.Parse(dropFileType.SelectedValue);
         UpFile.FilePath = fileName;
         if (FileMng.AddFile(UpFile))
             lblTip.Text = "文件上传非常成功 !";
         else
             lblTip.Text = "文件上传失败 !";
     }
     catch
     {
         lblTip.Text = "文件上传失败 !";
     }
 }
Beispiel #7
0
        public UploadFileBuilder Add()
        {
            var file = new UploadFile();

            container.Files.Add(file);

            return new UploadFileBuilder(file);
        }
 public string UploadFile()
 {
     UploadFile ui = new UploadFile();
     ui.SetMaxSizeM(5);
     ui.SetFileType(".docx,.txt,.doc,.jpg,.gif,.xls,.xlsx");//配在webConfig中
     string saveFolder = "/areas/formcontrol/views/_upload/temp/file/";
     ui.SetFileDirectory(saveFolder);
     HttpPostedFile file = System.Web.HttpContext.Current.Request.Files[0];
     var reponseMessage = ui.Save(file);
     return (reponseMessage).ModelToJson();
 }
        public static UploadResult Execute(string authToken, long fileId,
            UploadFile file, bool share, string message, string[] emails)
        {
            var uri = uriBase + authToken + "/" + fileId;
            if (DumpUri) Console.WriteLine("URI: " + uri);

            var files = new UploadFile[]
            {
                file
            };
            return UploadFunctionCore.Execute<UploadResult>(uri, files, share, message, emails, DumpContent, DumpXml);
        }
        public string Save(string catalog, string fileName, string contentType, Stream data)
        {
            string fileKey;
            var uploadFile = new UploadFile(data, null, fileName, contentType);
            var response = _client.Save(catalog, uploadFile);
            var result = CommandResult.Create(response);
            if (result.StatusCode == StatusCodes.Success)
                fileKey = result.Results["fileKeys"];
            else
                throw new FileUploadException();

            return fileKey;
        }
Beispiel #11
0
 public void FS_Upload(Auth auth, UploadFile request, UploadFile_Logic logic, CommonResponse ecr, string[] token, string uri)
 {
     if (auth.AuthResult(token, uri))
                                         {
                                                         ecr.data.results = logic.upload(request);
                                                         ecr.meta.code = 200;
                                                         ecr.meta.message = "OK";
                                         }
                                         else
                                         {
                                                         ecr.meta.code = 401;
                                                         ecr.meta.message = "Unauthorized";
                                         }
 }
        public void SavePic()
        {
            if (ctx.HasUploadFiles == false) {
                echoRedirect( "不能上传空图片", Index );
                return;
            }

            HttpFile file = ctx.GetFileSingle();
            Result result = Uploader.SaveImg( file );
            string savedPath = result.Info.ToString();

            UploadFile f = new UploadFile();
            f.Name = file.FileName;
            f.Path = savedPath;
            f.FileType = (int)FileType.Pic;
            f.insert();

            redirect( Index );
        }
Beispiel #13
0
        //上传图片
        protected void imageUpload_tj(object sender, EventArgs e)
        {
            UploadFile imageObj = new UploadFile();
            imageObj.MaxFileSize = 1024;  //最多只能上传1M的文件大小
            imageObj.FileType = "jpg|jepg|bmp";
            string imagePath = Server.MapPath("~/tmpupload/");

            //上传图片并保存
            imageObj.UploadFileGo(imagePath, imageUploader);
            if (imageObj.UploadState == false)
            {
                uploadInfo.Text = "";
                uploadInfo.Text = "上传失败:" + imageObj.UploadInfo;
            }
            else
            {
                uploadInfo.Text = "Tips:上传图片的格式为jpg,jepg,bmp,小于1M";
                imageToModify.ImageUrl = "tmpupload/" + imageObj.NewFileName;
                //限制图片的高度和宽度
                System.Drawing.Image img = System.Drawing.Image.FromFile(Server.MapPath("~/tmpupload/") + imageObj.NewFileName);
                int height = img.Height;
                int width = img.Width;
                if (width >= height)
                {
                    imageToModify.Style["width"] = "640px";
                    imageToModify.Style["height"] = (640.0 * height / width).ToString() + "px";
                }
                else
                {
                    imageToModify.Style["width"] = (640.0 * width / height).ToString() + "px";
                    imageToModify.Style["height"] = "640px";
                }
                hiddenHW.Value = width.ToString() + "," + height.ToString();
                hiddenFileName.Value = imageObj.NewFileName;
                modify.Style["display"] = "block";  //最后才显示图片
            }
        }
Beispiel #14
0
        public static IObservable<ApiResponse<User>> AccountUpdateProfileBackgroundImage(
            this AccessToken info,
            UploadFile image,
            bool? tile = null,
            bool? includeEntities = null,
            bool? skipStatus = null,
            bool? use = null)
        {
            var param = new ParameterCollection
            {
                {"image", image},
                {"tile", tile},
                {"include_entities", includeEntities},
                {"skip_status", skipStatus},
                {"use", use}
            };

            return info
                .GetClient()
                .SetEndpoint(Endpoints.AccountUpdateProfileBackgroundImage, HttpMethod.Post)
                .SetParameters(param)
                .GetResponse()
                .ReadResponse<User>();
        }
        public async Task <dynamic> UploadObject([FromForm] UploadFile input)
        {
            // get the uploaded file and save on the server
            var fileSavePath = Path.Combine(_env.ContentRootPath, input.fileToUpload.FileName);

            using (var stream = new FileStream(fileSavePath, FileMode.Create))
                await input.fileToUpload.CopyToAsync(stream);

            // user credentials
            Credentials = await Credentials.FromSessionAsync(base.Request.Cookies, Response.Cookies);

            // extract projectId and folderId from folderHref
            string[] hrefParams = input.folderHref.Split("/");
            string   projectId  = hrefParams[hrefParams.Length - 3];
            string   folderId   = hrefParams[hrefParams.Length - 1];

            // prepare storage
            ProjectsApi projectApi = new ProjectsApi();

            projectApi.Configuration.AccessToken = Credentials.TokenInternal;
            StorageRelationshipsTargetData       storageRelData = new StorageRelationshipsTargetData(StorageRelationshipsTargetData.TypeEnum.Folders, folderId);
            CreateStorageDataRelationshipsTarget storageTarget  = new CreateStorageDataRelationshipsTarget(storageRelData);
            CreateStorageDataRelationships       storageRel     = new CreateStorageDataRelationships(storageTarget);
            BaseAttributesExtensionObject        attributes     = new BaseAttributesExtensionObject(string.Empty, string.Empty, new JsonApiLink(string.Empty), null);
            CreateStorageDataAttributes          storageAtt     = new CreateStorageDataAttributes(input.fileToUpload.FileName, attributes);
            CreateStorageData storageData    = new CreateStorageData(CreateStorageData.TypeEnum.Objects, storageAtt, storageRel);
            CreateStorage     storage        = new CreateStorage(new JsonApiVersionJsonapi(JsonApiVersionJsonapi.VersionEnum._0), storageData);
            dynamic           storageCreated = await projectApi.PostStorageAsync(projectId, storage);

            string[] storageIdParams = ((string)storageCreated.data.id).Split('/');
            string[] bucketKeyParams = storageIdParams[storageIdParams.Length - 2].Split(':');
            string   bucketKey       = bucketKeyParams[bucketKeyParams.Length - 1];
            string   objectName      = storageIdParams[storageIdParams.Length - 1];

            // upload the file/object, which will create a new object
            ObjectsApi objects = new ObjectsApi();

            objects.Configuration.AccessToken = Credentials.TokenInternal;

            // get file size
            long fileSize = (new FileInfo(fileSavePath)).Length;

            // decide if upload direct or resumable (by chunks)
            if (fileSize > UPLOAD_CHUNK_SIZE * 1024 * 1024) // upload in chunks
            {
                long chunkSize      = 2 * 1024 * 1024;      // 2 Mb
                long numberOfChunks = (long)Math.Round((double)(fileSize / chunkSize)) + 1;

                long start = 0;
                chunkSize = (numberOfChunks > 1 ? chunkSize : fileSize);
                long   end       = chunkSize;
                string sessionId = Guid.NewGuid().ToString();

                // upload one chunk at a time
                using (BinaryReader reader = new BinaryReader(new FileStream(fileSavePath, FileMode.Open)))
                {
                    for (int chunkIndex = 0; chunkIndex < numberOfChunks; chunkIndex++)
                    {
                        string range = string.Format("bytes {0}-{1}/{2}", start, end, fileSize);

                        long         numberOfBytes = chunkSize + 1;
                        byte[]       fileBytes     = new byte[numberOfBytes];
                        MemoryStream memoryStream  = new MemoryStream(fileBytes);
                        reader.BaseStream.Seek((int)start, SeekOrigin.Begin);
                        int count = reader.Read(fileBytes, 0, (int)numberOfBytes);
                        memoryStream.Write(fileBytes, 0, (int)numberOfBytes);
                        memoryStream.Position = 0;

                        await objects.UploadChunkAsync(bucketKey, objectName, (int)numberOfBytes, range, sessionId, memoryStream);

                        start     = end + 1;
                        chunkSize = ((start + chunkSize > fileSize) ? fileSize - start - 1 : chunkSize);
                        end       = start + chunkSize;
                    }
                }
            }
            else // upload in a single call
            {
                using (StreamReader streamReader = new StreamReader(fileSavePath))
                {
                    await objects.UploadObjectAsync(bucketKey, objectName, (int)streamReader.BaseStream.Length, streamReader.BaseStream, "application/octet-stream");
                }
            }

            // cleanup
            string fileName = input.fileToUpload.FileName;

            System.IO.File.Delete(fileSavePath);

            // check if file already exists...
            FoldersApi folderApi = new FoldersApi();

            folderApi.Configuration.AccessToken = Credentials.TokenInternal;
            var filesInFolder = await folderApi.GetFolderContentsAsync(projectId, folderId);

            string itemId = string.Empty;

            foreach (KeyValuePair <string, dynamic> item in new DynamicDictionaryItems(filesInFolder.data))
            {
                if (item.Value.attributes.displayName == fileName)
                {
                    itemId = item.Value.id; // this means a file with same name is already there, so we'll create a new version
                }
            }
            // now decide whether create a new item or new version
            if (string.IsNullOrWhiteSpace(itemId))
            {
                // create a new item
                BaseAttributesExtensionObject        baseAttribute                   = new BaseAttributesExtensionObject(projectId.StartsWith("a.") ? "items:autodesk.core:File" : "items:autodesk.bim360:File", "1.0");
                CreateItemDataAttributes             createItemAttributes            = new CreateItemDataAttributes(fileName, baseAttribute);
                CreateItemDataRelationshipsTipData   createItemRelationshipsTipData  = new CreateItemDataRelationshipsTipData(CreateItemDataRelationshipsTipData.TypeEnum.Versions, CreateItemDataRelationshipsTipData.IdEnum._1);
                CreateItemDataRelationshipsTip       createItemRelationshipsTip      = new CreateItemDataRelationshipsTip(createItemRelationshipsTipData);
                StorageRelationshipsTargetData       storageTargetData               = new StorageRelationshipsTargetData(StorageRelationshipsTargetData.TypeEnum.Folders, folderId);
                CreateStorageDataRelationshipsTarget createStorageRelationshipTarget = new CreateStorageDataRelationshipsTarget(storageTargetData);
                CreateItemDataRelationships          createItemDataRelationhips      = new CreateItemDataRelationships(createItemRelationshipsTip, createStorageRelationshipTarget);
                CreateItemData createItemData = new CreateItemData(CreateItemData.TypeEnum.Items, createItemAttributes, createItemDataRelationhips);
                BaseAttributesExtensionObject      baseAttExtensionObj = new BaseAttributesExtensionObject(projectId.StartsWith("a.") ? "versions:autodesk.core:File" : "versions:autodesk.bim360:File", "1.0");
                CreateStorageDataAttributes        storageDataAtt      = new CreateStorageDataAttributes(fileName, baseAttExtensionObj);
                CreateItemRelationshipsStorageData createItemRelationshipsStorageData = new CreateItemRelationshipsStorageData(CreateItemRelationshipsStorageData.TypeEnum.Objects, storageCreated.data.id);
                CreateItemRelationshipsStorage     createItemRelationshipsStorage     = new CreateItemRelationshipsStorage(createItemRelationshipsStorageData);
                CreateItemRelationships            createItemRelationship             = new CreateItemRelationships(createItemRelationshipsStorage);
                CreateItemIncluded includedVersion = new CreateItemIncluded(CreateItemIncluded.TypeEnum.Versions, CreateItemIncluded.IdEnum._1, storageDataAtt, createItemRelationship);
                CreateItem         createItem      = new CreateItem(new JsonApiVersionJsonapi(JsonApiVersionJsonapi.VersionEnum._0), createItemData, new List <CreateItemIncluded>()
                {
                    includedVersion
                });

                ItemsApi itemsApi = new ItemsApi();
                itemsApi.Configuration.AccessToken = Credentials.TokenInternal;
                var newItem = await itemsApi.PostItemAsync(projectId, createItem);

                return(newItem);
            }
            else
            {
                // create a new version
                BaseAttributesExtensionObject          attExtensionObj              = new BaseAttributesExtensionObject(projectId.StartsWith("a.") ? "versions:autodesk.core:File" : "versions:autodesk.bim360:File", "1.0");
                CreateStorageDataAttributes            storageDataAtt               = new CreateStorageDataAttributes(fileName, attExtensionObj);
                CreateVersionDataRelationshipsItemData dataRelationshipsItemData    = new CreateVersionDataRelationshipsItemData(CreateVersionDataRelationshipsItemData.TypeEnum.Items, itemId);
                CreateVersionDataRelationshipsItem     dataRelationshipsItem        = new CreateVersionDataRelationshipsItem(dataRelationshipsItemData);
                CreateItemRelationshipsStorageData     itemRelationshipsStorageData = new CreateItemRelationshipsStorageData(CreateItemRelationshipsStorageData.TypeEnum.Objects, storageCreated.data.id);
                CreateItemRelationshipsStorage         itemRelationshipsStorage     = new CreateItemRelationshipsStorage(itemRelationshipsStorageData);
                CreateVersionDataRelationships         dataRelationships            = new CreateVersionDataRelationships(dataRelationshipsItem, itemRelationshipsStorage);
                CreateVersionData versionData    = new CreateVersionData(CreateVersionData.TypeEnum.Versions, storageDataAtt, dataRelationships);
                CreateVersion     newVersionData = new CreateVersion(new JsonApiVersionJsonapi(JsonApiVersionJsonapi.VersionEnum._0), versionData);

                VersionsApi versionsApis = new VersionsApi();
                versionsApis.Configuration.AccessToken = Credentials.TokenInternal;
                dynamic newVersion = await versionsApis.PostVersionAsync(projectId, newVersionData);

                return(newVersion);
            }
        }
 public WindowsInstallerImpl(UploadFile uploadFile)
 {
     _uploadFile = uploadFile;
 }
Beispiel #17
0
        /// <summary>
        /// 得到保存或者修改的对象
        /// </summary>
        private void GetAddOrUpdatePersonnelInfo(out EyouSoft.BLL.AdminCenterStructure.PersonnelInfo bllPersonnel, out EyouSoft.Model.AdminCenterStructure.PersonnelInfo modelPersonnel)
        {
            #region "基本信息"
            FileNo   = Utils.GetFormValue("txt_FileNo");                        //档案编号
            Name     = Utils.GetFormValue("txt_Name");                          //姓名
            CardID   = Utils.GetFormValue("txt_CardID");                        //身份证号码
            Birthday = Utils.GetDateTimeNullable(Request.Form["txt_Birthday"]); //生日

            EntryDate = Utils.GetFormValue("txt_EntryDate");                    //入职日期
            //dpWorkLife = Utils.GetFormValue("dpWorkLife");           //工龄
            LeftDate  = Utils.GetFormValue("txt_LeftDate");                     //离职日期
            National  = Utils.GetFormValue("txt_National");                     //民族
            Political = Utils.GetFormValue("txt_Political");                    //政治面貌
            Telephone = Utils.GetFormValue("txt_Telephone");                    //联系电话
            Mobile    = Utils.GetFormValue("txt_Mobile");                       //手机
            QQ        = Utils.GetFormValue("txt_QQ");
            MSN       = Utils.GetFormValue("txt_MSN");
            Email     = Utils.GetFormValue("txt_Email");
            Address   = Utils.GetFormValue("txt_Address");
            Remark    = Utils.GetFormValue("txt_Remark");
            #endregion

            #region "学历信息"
            string[] keysGrade       = Utils.GetFormValues("EducationGrade");      //学历
            string[] keysState       = Utils.GetFormValues("EducationState");      //状态
            string[] RecordStartDate = Utils.GetFormValues("txt_RecordStartDate"); //开始时间
            string[] RecordEndDate   = Utils.GetFormValues("txt_RecordEndDate");   //结束时间
            string[] Profession      = Utils.GetFormValues("txt_Profession");      //专业
            string[] Graduation      = Utils.GetFormValues("txt_Graduation");      //毕业院校
            string[] RecordRemark    = Utils.GetFormValues("txt_RecordRemark");    //备注
            #endregion

            #region "履历信息"
            string[] ResumeStartDate = Utils.GetFormValues("txt_ResumeStartDate"); //开始时间
            string[] ResumeEndDate   = Utils.GetFormValues("txt_ResumeEndDate");   //结束时间
            string[] WorkPlace       = Utils.GetFormValues("txt_WorkPlace");       //工作地点
            string[] WorkUnit        = Utils.GetFormValues("txt_WorkUnit");        //工作单位
            string[] Job             = Utils.GetFormValues("txt_Job");             //职业
            string[] ResumeRemark    = Utils.GetFormValues("txt_ResumeRemark");    //备注
            #endregion

            bllPersonnel   = new EyouSoft.BLL.AdminCenterStructure.PersonnelInfo();
            modelPersonnel = new EyouSoft.Model.AdminCenterStructure.PersonnelInfo();

            #region 保存修改
            modelPersonnel.CompanyId    = CurrentUserCompanyID;
            modelPersonnel.ArchiveNo    = FileNo;
            modelPersonnel.UserName     = Name;
            modelPersonnel.ContactSex   = (EyouSoft.Model.EnumType.CompanyStructure.Sex) this.dpSex.SelectedIndex;
            modelPersonnel.CardId       = CardID;
            modelPersonnel.BirthDate    = Birthday;
            modelPersonnel.DepartmentId = this.ucDepartemnt.GetDepartId;


            HttpPostedFile hpf      = this.Request.Files["FileEmployeePicture"];
            bool           Result   = false;
            string         fileName = string.Empty;
            string         oldeName = string.Empty;
            if (hpf != null && hpf.ContentLength > 0)
            {
                Result = UploadFile.FileUpLoad(hpf, "workerPhoto", out fileName, out oldeName);
                modelPersonnel.PhotoPath = fileName;                              //上转照片
            }
            else
            {
                modelPersonnel.PhotoPath = this.hiddenPhoto.Value;
            }
            modelPersonnel.DutyName = ddlJobPostion.SelectedValue;
            string m = this.ddlJobPostion.Text;
            modelPersonnel.DutyId = Utils.GetIntNull(Utils.GetFormValue(this.ddlJobPostion.UniqueID));//职务ID

            modelPersonnel.IsLeave      = this.dpWorkerState.Value == "1" ? true : false;
            modelPersonnel.PersonalType = (EyouSoft.Model.EnumType.AdminCenterStructure.PersonalType)Utils.GetInt(this.dpWorkerType.Value);
            //modelPersonnel.WorkYear = Utils.GetInt(dpWorkLife);
            modelPersonnel.EntryDate = Utils.GetDateTimeNullable(EntryDate);

            modelPersonnel.IsMarried      = this.dpMarriageState.Value == "1" ? true : false;
            modelPersonnel.LeaveDate      = Utils.GetDateTimeNullable(LeftDate);
            modelPersonnel.National       = National;
            modelPersonnel.Birthplace     = this.ucProvince1.ProvinceId + "," + this.ucCity1.CityId;
            modelPersonnel.Politic        = Political;
            modelPersonnel.ContactTel     = Telephone;
            modelPersonnel.ContactMobile  = Mobile;
            modelPersonnel.QQ             = QQ;
            modelPersonnel.Email          = Email;
            modelPersonnel.MSN            = MSN;
            modelPersonnel.ContactAddress = Address;
            modelPersonnel.Remark         = Remark;

            #region 学历信息
            IList <EyouSoft.Model.AdminCenterStructure.SchoolInfo> listSchool  = new List <EyouSoft.Model.AdminCenterStructure.SchoolInfo>();
            EyouSoft.Model.AdminCenterStructure.SchoolInfo         modelSchool = null;
            if (RecordStartDate != null && RecordStartDate.Length > 0)
            {
                for (int index = 0; index < RecordStartDate.Length; index++)
                {
                    if (!string.IsNullOrEmpty(RecordStartDate[index].Trim()) && !string.IsNullOrEmpty(RecordEndDate[index].Trim()) && (!string.IsNullOrEmpty(Utils.GetFormValue(keysGrade[index]).Trim()) || !string.IsNullOrEmpty(Profession[index].Trim()) || !string.IsNullOrEmpty(Graduation[index].Trim()) || !string.IsNullOrEmpty(Utils.GetFormValue(keysState[index]).Trim()) || !string.IsNullOrEmpty(RecordRemark[index].Trim())))
                    {
                        modelSchool              = new EyouSoft.Model.AdminCenterStructure.SchoolInfo();
                        modelSchool.StartDate    = Utils.GetDateTimeNullable(RecordStartDate[index].Trim());
                        modelSchool.EndDate      = Utils.GetDateTimeNullable(RecordEndDate[index].Trim());
                        modelSchool.Degree       = (EyouSoft.Model.EnumType.AdminCenterStructure.DegreeType)Utils.GetInt(keysGrade[index]);
                        modelSchool.Professional = Utils.InputText(Profession[index].Trim());
                        modelSchool.SchoolName   = Utils.InputText(Graduation[index].Trim());
                        modelSchool.StudyStatus  = Convert.ToBoolean(Utils.GetInt(keysState[index]));
                        modelSchool.Remark       = Utils.InputText(RecordRemark[index].Trim());
                        listSchool.Add(modelSchool);
                    }
                }
                if (listSchool.Count > 0)
                {
                    modelPersonnel.SchoolList = listSchool;
                }
            }
            #endregion

            #region 履历信息
            IList <EyouSoft.Model.AdminCenterStructure.PersonalHistory> listHistory  = new List <EyouSoft.Model.AdminCenterStructure.PersonalHistory>();
            EyouSoft.Model.AdminCenterStructure.PersonalHistory         modelHistory = null;
            if (ResumeStartDate != null && ResumeStartDate.Length > 0)
            {
                for (int index = 0; index < ResumeStartDate.Length; index++)
                {
                    if (!string.IsNullOrEmpty(ResumeStartDate[index].Trim()) && !string.IsNullOrEmpty(ResumeEndDate[index].Trim()) && (!string.IsNullOrEmpty(WorkPlace[index].Trim()) || !string.IsNullOrEmpty(WorkUnit[index].Trim()) || !string.IsNullOrEmpty(Job[index].Trim()) || !string.IsNullOrEmpty(ResumeRemark[index].Trim())))
                    {
                        modelHistory           = new EyouSoft.Model.AdminCenterStructure.PersonalHistory();
                        modelHistory.StartDate = Utils.GetDateTimeNullable(ResumeStartDate[index].Trim());
                        modelHistory.EndDate   = Utils.GetDateTimeNullable(ResumeEndDate[index].Trim());
                        modelHistory.WorkPlace = Utils.InputText(WorkPlace[index].Trim());
                        modelHistory.WorkUnit  = Utils.InputText(WorkUnit[index].Trim());
                        modelHistory.TakeUp    = Utils.InputText(Job[index].Trim());
                        modelHistory.Remark    = Utils.InputText(ResumeRemark[index].Trim());
                        listHistory.Add(modelHistory);
                    }
                }
                if (listHistory != null && listHistory.Count > 0)
                {
                    modelPersonnel.HistoryList = listHistory;
                }
            }
            #endregion

            #endregion
        }
Beispiel #18
0
    protected void btnSave_Click(object sender, EventArgs e)
    {
        int b = 0;

        if (ddlDirectory.SelectedIndex == 0)
        {
            DisplayMessage("Select Directory Name");
            ddlDirectory.Focus();
            return;
        }
        if (ddlDocumentName.SelectedIndex == 0)
        {
            DisplayMessage("Select Document Name");
            ddlDocumentName.Focus();
            return;
        }


        if (txtFileName.Text == "")
        {
            DisplayMessage("Enter File Name");
            txtFileName.Focus();
            return;
        }


        if (UploadFile.HasFile == false)
        {
            DisplayMessage("Upload The File");
            UploadFile.Focus();
            return;
        }


        string filepath = "~/" + "ArcaWing" + "/" + ddlDirectory.SelectedItem + "/" + UploadFile.FileName;

        UploadFile.SaveAs(Server.MapPath(filepath));
        string filename = UploadFile.FileName;
        string ext      = Path.GetExtension(filepath);

        string NewfileName = txtFileName.Text + "" + ext;

        Stream       fs = UploadFile.PostedFile.InputStream;
        BinaryReader br = new BinaryReader(fs);

        Byte[] bytes = br.ReadBytes((Int32)fs.Length);

        if (editid.Value == "")
        {
            string FileTypeId = "0";

            DataTable dt = ObjFile.Get_FileTransaction(strCompId, FileTypeId);


            dt = new DataView(dt, "File_Name='" + txtFileName.Text + "'", "", DataViewRowState.CurrentRows).ToTable();
            if (dt.Rows.Count > 0)
            {
                DisplayMessage("File Name Already Exists");
                txtFileName.Focus();
                txtFileName.Text = "";
                return;
            }
            //dt = new DataView(dt, "Directory_Id="+ddlDirectory.SelectedValue+" ", "", DataViewRowState.CurrentRows).ToTable();
            //if (dt.Rows.Count > 0)
            //{
            //    DisplayMessage("Directory Exists");
            //    txtContentName.Focus();
            //    return;

            //}



            b = ObjFile.Insert_In_FileTransaction(strCompId, ddlDirectory.SelectedValue, ddlDocumentName.SelectedValue, "0", NewfileName, DateTime.Now.ToString(), bytes, filepath, txtExpiryDate.Text, "", "0", "", "", "", false.ToString(), DateTime.Now.ToString(), true.ToString(), Session["UserId"].ToString(), DateTime.Now.ToString(), Session["UserId"].ToString(), DateTime.Now.ToString());

            if (b != 0)
            {
                DisplayMessage("Record Saved");
                FillGrid();
                Reset();
            }
            else
            {
                DisplayMessage("Record Not Saved");
            }
        }
        else
        {
            string    FileTransactionid = "0";
            DataTable dt = ObjFile.Get_FileTransaction(strCompId, FileTransactionid);


            string FileTransaction = string.Empty;


            try
            {
                FileTransaction = (new DataView(dt, "Trans_Id='" + editid.Value + "'", "", DataViewRowState.CurrentRows).ToTable()).Rows[0]["File_Name"].ToString();
            }
            catch
            {
                FileTransaction = "";
            }
            dt = new DataView(dt, "File_Name='" + txtFileName.Text + "' and File_Name<>'" + FileTransaction + "'  ", "", DataViewRowState.CurrentRows).ToTable();
            if (dt.Rows.Count > 0)
            {
                DisplayMessage("File Name Already Exists");
                txtFileName.Focus();
                txtFileName.Text = "";
                return;
            }
            //dt = new DataView(dt, "Content_Type='" + txtContentName.Text + "'  ", "", DataViewRowState.CurrentRows).ToTable();
            //if (dt.Rows.Count > 0)
            //{
            //    DisplayMessage("Content Name Already Exists");
            //    txtContentName.Focus();
            //    return;

            //}



            b = ObjFile.Update_In_FileTransaction(strCompId, editid.Value, ddlDirectory.SelectedValue, ddlDocumentName.SelectedValue, ddlFiletype.SelectedValue, NewfileName, DateTime.Now.ToString(), bytes, filepath, DateTime.Now.ToString(), "", "0", "", "", "", false.ToString(), DateTime.Now.ToString(), true.ToString(), Session["UserId"].ToString(), DateTime.Now.ToString());

            if (b != 0)
            {
                btnList_Click(null, null);
                DisplayMessage("Record Updated");
                Reset();
                FillGrid();
            }
            else
            {
                DisplayMessage("Record Not Updated");
            }
        }
    }
Beispiel #19
0
        private void OpenLabel_MouseDown(object sender, MouseButtonEventArgs e)
        {
            Label label = sender as Label;

            UploadFile uploadFile = null;

            foreach (UploadFile uf in this.upfiles)
            {
                if (uf.FilePath.Equals(label.Tag.ToString()))
                {
                    uploadFile = uf;
                }
            }
            if (uploadFile != null)
            {
                if (label.Content.Equals(UploadFile.OPENDOC))
                {
                    String doc = uploadFile.FilePath.Substring(0, uploadFile.FilePath.Length - uploadFile.FilePath.Split('\\')[uploadFile.FilePath.Split('\\').Length - 1].Length);
                    System.Diagnostics.Process.Start("explorer.exe ", doc);
                }
                else if (label.Content.Equals(UploadFile.REUPLOAD))
                {
                    String token = CacheService.Instance.GetStuToken();

                    FileResult fr = rf.UploadFile(uploadFile.FilePath, token);

                    //获取文件名字
                    String file_name = uploadFile.FilePath.Split('\\')[uploadFile.FilePath.Split('\\').Length - 1];

                    if (fr != null)
                    {
                        if (fr.code == "200")
                        {
                            //关联文件与记录
                            List <Attach> attaches = new List <Attach>();
                            foreach (Student s in CacheService.Instance.GetStudentList())
                            {
                                Attach a = new Attach {
                                    subjectId = s.RecordId, ownerId = s.Id, type = "EXPERIMENT_RECORD_FILE"
                                };
                                attaches.Add(a);
                            }

                            AttachResult ar = rf.AttachRecordWithFile(CacheService.Instance.ExperimentId, fr.data.id, attaches, CacheService.Instance.GetStuToken());

                            if (ar != null)
                            {
                                if (ar.code == "200")
                                {
                                    uploadFile.Status    = UploadFile.SUCCESS;
                                    uploadFile.Color     = "#FF979797";
                                    uploadFile.Operation = UploadFile.OPENDOC;
                                    fileList.Items.Refresh();
                                }
                                else
                                {
                                    LSMessageBox.Show("关联文件错误", ar.message);
                                    uploadFile.Status    = UploadFile.FAIL;
                                    uploadFile.Color     = "Red";
                                    uploadFile.Operation = UploadFile.REUPLOAD;
                                    fileList.Items.Refresh();
                                }
                            }
                            else
                            {
                                LSMessageBox.Show("网络错误", "网络异常");
                                uploadFile.Status    = UploadFile.FAIL;
                                uploadFile.Color     = "Red";
                                uploadFile.Operation = UploadFile.REUPLOAD;
                                fileList.Items.Refresh();
                            }
                        }
                        else
                        {
                            LSMessageBox.Show("上传文件错误", fr.message);
                            uploadFile.Status    = UploadFile.FAIL;
                            uploadFile.Color     = "Red";
                            uploadFile.Operation = UploadFile.REUPLOAD;
                            fileList.Items.Refresh();
                        }
                    }
                    else
                    {
                        LSMessageBox.Show("网络错误", "网络异常");
                        uploadFile.Status    = UploadFile.FAIL;
                        uploadFile.Color     = "Red";
                        uploadFile.Operation = UploadFile.REUPLOAD;
                        fileList.Items.Refresh();
                    }
                }
            }
        }
Beispiel #20
0
        private void PublishMod(UIMouseEvent evt, UIElement listeningElement)
        {
            if (ModLoader.modBrowserPassphrase == "")
            {
                Main.menuMode = Interface.enterPassphraseMenuID;
                Interface.enterPassphraseMenu.SetGotoMenu(Interface.modSourcesID);
                return;
            }
            Main.PlaySound(10);
            try {
                var modFile = _builtMod.modFile;
                var bp      = _builtMod.properties;

                var files = new List <UploadFile>();
                files.Add(new UploadFile {
                    Name     = "file",
                    Filename = Path.GetFileName(modFile.path),
                    //    ContentType = "text/plain",
                    Content = File.ReadAllBytes(modFile.path)
                });
                if (modFile.HasFile("icon.png"))
                {
                    using (modFile.Open())
                        files.Add(new UploadFile {
                            Name     = "iconfile",
                            Filename = "icon.png",
                            Content  = modFile.GetBytes("icon.png")
                        });
                }
                if (bp.beta)
                {
                    throw new WebException(Language.GetTextValue("tModLoader.BetaModCantPublishError"));
                }
                if (bp.buildVersion != modFile.tModLoaderVersion)
                {
                    throw new WebException(Language.GetTextValue("OutdatedModCantPublishError.BetaModCantPublishError"));
                }

                var values = new NameValueCollection
                {
                    { "displayname", bp.displayName },
                    { "displaynameclean", string.Join("", ChatManager.ParseMessage(bp.displayName, Color.White).Where(x => x.GetType() == typeof(TextSnippet)).Select(x => x.Text)) },
                    { "name", modFile.name },
                    { "version", "v" + bp.version },
                    { "author", bp.author },
                    { "homepage", bp.homepage },
                    { "description", bp.description },
                    { "steamid64", ModLoader.SteamID64 },
                    { "modloaderversion", "tModLoader v" + modFile.tModLoaderVersion },
                    { "passphrase", ModLoader.modBrowserPassphrase },
                    { "modreferences", String.Join(", ", bp.modReferences.Select(x => x.mod)) },
                    { "modside", bp.side.ToFriendlyString() },
                };
                if (values["steamid64"].Length != 17)
                {
                    throw new WebException($"The steamid64 '{values["steamid64"]}' is invalid, verify that you are logged into Steam and don't have a pirated copy of Terraria.");
                }
                if (string.IsNullOrEmpty(values["author"]))
                {
                    throw new WebException($"You need to specify an author in build.txt");
                }
                ServicePointManager.Expect100Continue = false;
                string url = "http://javid.ddns.net/tModLoader/publishmod.php";
                using (PatientWebClient client = new PatientWebClient()) {
                    ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, policyErrors) => true;
                    Interface.progress.Show(displayText: $"Uploading: {modFile.name}", gotoMenu: Interface.modSourcesID, cancel: client.CancelAsync);
                    client.UploadProgressChanged += (s, e) => Interface.progress.Progress = (float)e.BytesSent / e.TotalBytesToSend;
                    client.UploadDataCompleted   += (s, e) => PublishUploadDataComplete(s, e, modFile);

                    var boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x", System.Globalization.NumberFormatInfo.InvariantInfo);
                    client.Headers["Content-Type"] = "multipart/form-data; boundary=" + boundary;
                    //boundary = "--" + boundary;
                    byte[] data = UploadFile.GetUploadFilesRequestData(files, values);
                    client.UploadDataAsync(new Uri(url), data);
                }
            }
            catch (WebException e) {
                UIModBrowser.LogModBrowserException(e);
            }
        }
Beispiel #21
0
 async public Task <string> UploadFile(UploadFile model, string folderId, string customerId)
 {
     return(await PostAsync <string>($"api/v1/folder/{folderId}/customer/{customerId}/file", model));
 }
 /// <summary>添加--UploadFile</summary>
 /// <param name="model">UploadFile实体</param>
 /// <returns></returns>
 public void Add_UploadFile(UploadFile model)
 {
     model.Save();
 }
        /// <returns>上传成功返回"",并填充 Model.UploadFile</returns>
        /// <param name="vid">上传配置模块id,即UploadConfig_Id</param>
        /// <param name="key">随机key</param>
        /// <param name="userId">上传者id</param>
        /// <param name="userName">上传者UserName</param>
        /// <param name="remotePicUrl">远程图片的url地址</param>
        /// <param name="m_r">Model.UploadFile</param>
        /// <returns>上传成功返回"",并填充 Model.UploadFile</returns>
        public string Upload_RemotePic(int vid, string key, int userId, string userName, string remotePicUrl, UploadFile m_r)
        {
            #region 检查参数
            //---------------------------------------------------
            if (vid < 1 || key.Length < 10)
            {
                return("缺少参数:key或sid");
            }
            //---------------------------------------------------

            #region 检查登陆
            m_r.UserId   = userId;
            m_r.UserName = userName;

            if (m_r.UserId == 0)
            {
                return("您的权限不足!");
            }
            #endregion

            //---------------------------------------------------
            UploadConfig mC = Read_UploadConfig(vid);
            if (mC.Id != vid)
            {
                return("缺少参数:UploadConfig_Id!");
            }

            if (mC.IsPost != 1)
            {
                return("系统暂时禁止上传文件2!");
            }

            if (mC.IsEditor != 1)
            {
                return("非编辑器类别!");
            }

            mC.UploadType_TypeKey = "image";
            #endregion


            //----------------------------------------------
            #region 生成暂时目录
            string sCfgSavePath = new Uploader().SavePath;
            string sSavePath    = DirFileHelper.FixDirPath(sCfgSavePath + mC.SaveDir) + DateTime.Now.ToString("yyMM") + "/";
            if (!DirFileHelper.CheckSaveDir(sSavePath))
            {
                return("SavePath设置不当:" + sSavePath + ", 或权限不足!");
            }

            string sServerDir = sCfgSavePath + "remote/";
            if (!DirFileHelper.CheckSaveDir(sServerDir))
            {
                return("ServerDir设置不当:" + sServerDir + ", 或权限不足!");
            }
            //----------------------------------------------
            string sSrcName = StringHelper.Left(DirFileHelper.GetFileName(remotePicUrl), 90);
            string sFileExt = DirFileHelper.GetFileExtension(sSrcName);

            //因部部分网站不是标准的jpg、gif扩展名,所以修改下面代码
            if (sFileExt.Length > 0)
            {
                string sAllowed = ",jpg,gif,png,bmp,";
                string sExt     = "," + sFileExt.ToLower() + ",";
                if (sAllowed.IndexOf(sExt) == -1)
                {
                    sFileExt = "jpg";
                }
            }
            else
            {
                sFileExt = "jpg";
            }
            //----------------------------------------------

            string sNewFile = DirFileHelper.GetRndFileName("." + sFileExt);

            if (sServerDir.IndexOf(":") < 0)
            {
                sServerDir = DirFileHelper.FixDirPath(DirFileHelper.GetMapPath(sServerDir));
            }
            string sNewRoot = System.IO.Path.Combine(sServerDir, sNewFile);
            #endregion

            //----------------------------------------------
            #region   到暂时目录
            try
            {
                var wc = new System.Net.WebClient();
                wc.DownloadFile(remotePicUrl, sNewRoot);
            }
            catch (Exception ex)
            {
                //throw ex;
                return(ex.Message.ToLower());
            }

            if (!DirFileHelper.IsExistFile(sNewRoot))
            {
                return("上传失败");
            }
            #endregion

            //----------------------------------------------
            #region 判断是否真实图片格式,并取得图片宽高
            int ww = 0, hh = 0;
            if (!Uploader.Get_Pic_WW_HH(sNewRoot, out ww, out hh))
            {
                DirFileHelper.DeleteFile(sNewRoot);
                return("非法格式!不是图片文件。");
            }

            int  iMaxSize  = mC.PicSize;
            long iFileSize = DirFileHelper.GetFileSize(sNewRoot);

            /*
             * if (iFileSize > iMaxSize)
             * {
             *  return "上传文件大小超过了限制.最多上传(" + DirFileHelper.FmtFileSize2(iMaxSize) + ").";
             * }
             */
            #endregion


            #region 把上传的暂时文件复制到相关模块目录中
            string sNewPath = sSavePath + sNewFile;
            string orgImg   = DirFileHelper.GetFilePathPostfix(sNewPath, "o");

            //复制到原始图
            DirFileHelper.CopyFile(sNewRoot, orgImg);

            //删除暂时上传的图片
            DirFileHelper.DeleteFile(sNewRoot);

            //生成相关缩略图
            OneMakeThumbImage(sNewPath, mC);

            #endregion


            //----------------------------------------------
            #region 保存入数据库
            m_r.UploadConfig_Id = mC.Id;
            m_r.JoinName        = mC.JoinName;
            m_r.JoinId          = 0;

            m_r.UserType = mC.UserType;
            m_r.UserIp   = IpHelper.GetUserIp();
            m_r.AddDate  = DateTime.Now;
            m_r.InfoText = "";
            m_r.RndKey   = key;

            m_r.Name = sNewFile;
            m_r.Path = sNewPath;
            m_r.Src  = sSrcName;
            m_r.Ext  = sFileExt;

            m_r.Size      = ConvertHelper.Cint0(iFileSize);
            m_r.PicWidth  = ww;
            m_r.PicHeight = hh;

            //保存入数据库
            Add_UploadFile(m_r);
            #endregion

            //------------------------------------
            //上传成功,输出结果
            return("");
        }
        /// <returns>上传成功返回"",并填充 UploadFile(AspNet上传控件专用)</returns>
        /// <param name="oFile">System.Web.HttpPostedFile</param>
        /// <param name="vid">上传配置模块id,即Id</param>
        /// <param name="key">随机key</param>
        /// <param name="userId">上传者id</param>
        /// <param name="userName">上传者UserName</param>
        /// <param name="m_r">UploadFile</param>
        /// <param name="userType">0=未知,1=后台管理员上传,2=前台会员上传</param>
        /// <returns>上传成功返回"",并填充 UploadFile</returns>
        public string Upload_AspNet(System.Web.HttpPostedFile oFile, int vid, string key, int userId, string userName,
                                    UploadFile m_r, int userType = 1)
        {
            #region 检查参数
            //---------------------------------------------------
            if (vid < 1 || key.Length < 10)
            {
                return("缺少参数:key或sid");
            }


            //---------------------------------------------------
            UploadConfig mC = Read_UploadConfig(vid);
            if (mC.Id != vid)
            {
                return("缺少参数:Id!");
            }

            if (mC.IsPost != 1)
            {
                return("系统暂时禁止上传文件2!");
            }

            if (mC.IsEditor == 1)
            {
                return("非编辑器类别!");
            }
            #endregion

            //---------------------------------------------------
            #region 检查登陆
            m_r.UserId = 0;
            if (mC.UserType == 1)//管理员
            {
                if (userType == 1)
                {
                    m_r.UserId   = userId;
                    m_r.UserName = userName;
                }
            }
            else
            {
                if (userType == 2)//一般会员
                {
                    m_r.UserId   = userId;
                    m_r.UserName = userName;
                }
            }

            if (m_r.UserId == 0)
            {
                return("您的权限不足!");
            }
            #endregion

            //------------------------------------------------
            #region 设置上传参数
            var oUp = new Uploader();

            oUp.IsEnabled    = true;
            oUp.IsChkSrcPost = true;
            oUp.CutType      = ConvertHelper.Cint0(mC.CutType);
            oUp.AllowedExt   = Get_Ext(mC.UploadType_TypeKey);
            oUp.MaxSize      = (mC.UploadType_TypeKey == "image") ? ConvertHelper.Cint0(mC.PicSize) : ConvertHelper.Cint0(mC.FileSize);
            oUp.SavePath     = mC.SaveDir;


            oUp.SetPic((mC.IsFixPic == 1), ConvertHelper.Cint0(mC.PicWidth), ConvertHelper.Cint0(mC.PicHeight), ConvertHelper.Cint0(mC.PicQuality));
            oUp.SetBig((mC.IsBigPic == 1), ConvertHelper.Cint0(mC.BigWidth), ConvertHelper.Cint0(mC.BigHeight), ConvertHelper.Cint0(mC.BigQuality));
            oUp.SetMid((mC.IsMidPic == 1), ConvertHelper.Cint0(mC.MidWidth), ConvertHelper.Cint0(mC.MidHeight), ConvertHelper.Cint0(mC.MidQuality));
            oUp.SetMin((mC.IsMinPic == 1), ConvertHelper.Cint0(mC.MinWidth), ConvertHelper.Cint0(mC.MinHeight), ConvertHelper.Cint0(mC.MinQuality));
            oUp.SetHot((mC.IsHotPic == 1), ConvertHelper.Cint0(mC.HotWidth), ConvertHelper.Cint0(mC.HotHeight), ConvertHelper.Cint0(mC.HotQuality));

            oUp.IsWaterPic = (mC.IsWaterPic == 1);
            #endregion

            #region
            //------------------------------------------------
            bool isOk = oUp.UploadFile(oFile);
            if (!isOk)
            {
                //上传出错
                return(StringHelper.XssTextClear(oUp.GetErrMsg() + mC.Id));
            }
            #endregion

            //----------------------------------------------------------------
            #region 保存入数据库
            m_r.UploadConfig_Id = mC.Id;
            m_r.JoinName        = mC.JoinName;
            m_r.JoinId          = 0;

            m_r.UserType = mC.UserType;
            m_r.UserIp   = IpHelper.GetUserIp();
            m_r.AddDate  = DateTime.Now;
            m_r.InfoText = "";
            m_r.RndKey   = key;

            m_r.Name = oUp.NewFile;
            m_r.Path = oUp.NewPath;
            m_r.Src  = StringHelper.Left(oUp.SrcName, 90, false);
            m_r.Ext  = oUp.FileExt;

            m_r.Size      = oUp.GetFileSize();
            m_r.PicWidth  = oUp.NewWidth;
            m_r.PicHeight = oUp.NewHeight;

            //保存入数据库
            Add_UploadFile(m_r);
            #endregion

            //------------------------------------
            //上传成功,输出结果
            return("");
        }
        /// <returns>上传成功返回"",并填充 UploadFile</returns>
        /// <param name="vid">上传配置模块id,即Id</param>
        /// <param name="key">随机key</param>
        /// <param name="userId">上传者id</param>
        /// <param name="userName">上传者UserName</param>
        /// <param name="m_r">UploadFile</param>
        /// <param name="filePostName">上传文件框控件的名称,默认"imgFile",uploadify 默认 "Filedata"</param>
        /// <param name="userType">0=未知,1=后台管理员上传,2=前台会员上传</param>
        /// <param name="isEditor">从GetAction返回判断是否为编辑器</param>
        /// <param name="isSwf">是否通过flash上传</param>
        /// <returns>上传成功返回"",并填充 UploadFile</returns>
        public string Upload_Web(int vid, string key, int userId, string userName,
                                 UploadFile m_r, string filePostName = "imgFile",
                                 int userType = 1, bool isEditor = false, bool isSwf = false)
        {
            #region 检查参数
            //---------------------------------------------------
            if (vid < 1 || key.Length < 10)
            {
                return("缺少参数:key或sid");
            }

            string dir = RequestHelper.GetKeyChar("dir");//编辑器专用:image,flash,media,file
            if (dir.Length > 0)
            {
                if (Array.IndexOf("image,flash,media,file".Split(','), dir) == -1)
                {
                    return("缺少参数:dir");
                }
            }
            //---------------------------------------------------
            UploadConfig mC = Read_UploadConfig(vid);
            if (mC == null || mC.Id != vid)
            {
                return("缺少参数:上传配置Id设置不正确!");
            }

            if (mC.IsPost != 1)
            {
                return("系统暂时禁止上传文件2!");
            }

            if (mC.IsEditor == 1 && isEditor == false)
            {
                return("非编辑器类别!");
            }


            if (mC.IsSwf == 0 && isSwf == true)
            {
                return("不能从flash中上传!");
            }
            #endregion

            //---------------------------------------------------
            #region 检查登陆
            m_r.UserId = 0;
            if (mC.UserType == 1)//管理员
            {
                if (userType == 1)
                {
                    m_r.UserId   = userId;
                    m_r.UserName = userName;
                }
            }
            else
            {
                if (userType == 2)//一般会员
                {
                    m_r.UserId   = userId;
                    m_r.UserName = userName;
                }
            }

            if (m_r.UserId == 0)
            {
                return("您的权限不足!");
            }
            #endregion

            //------------------------------------------------
            #region 设置上传参数
            var oUp = new Uploader();

            oUp.IsEnabled = true;
            if (isSwf)
            {
                oUp.IsChkSrcPost = false;  //如果swf提交,必须设置为 o_up.isChkSrcPost = false;
            }
            else
            {
                //o_up.isChkSrcPost = (m_c.isChkSrcPost == "1");  //如果swf提交,必须设置为 o_up.isChkSrcPost = false;
                oUp.IsChkSrcPost = true;
            }

            oUp.CutType = ConvertHelper.Cint0(mC.CutType);

            oUp.FilePostName = filePostName;

            if (isEditor && mC.UploadType_TypeKey == "editor")
            {
                mC.UploadType_TypeKey = dir;
            }
            oUp.AllowedExt = Get_Ext(mC.UploadType_TypeKey);
            oUp.MaxSize    = (mC.UploadType_TypeKey == "image") ? ConvertHelper.Cint0(mC.PicSize) : ConvertHelper.Cint0(mC.FileSize);
            oUp.SavePath   = mC.SaveDir;


            oUp.SetPic((mC.IsFixPic == 1), ConvertHelper.Cint0(mC.PicWidth), ConvertHelper.Cint0(mC.PicHeight), ConvertHelper.Cint0(mC.PicQuality));
            oUp.SetBig((mC.IsBigPic == 1), ConvertHelper.Cint0(mC.BigWidth), ConvertHelper.Cint0(mC.BigHeight), ConvertHelper.Cint0(mC.BigQuality));
            oUp.SetMid((mC.IsMidPic == 1), ConvertHelper.Cint0(mC.MidWidth), ConvertHelper.Cint0(mC.MidHeight), ConvertHelper.Cint0(mC.MidQuality));
            oUp.SetMin((mC.IsMinPic == 1), ConvertHelper.Cint0(mC.MinWidth), ConvertHelper.Cint0(mC.MinHeight), ConvertHelper.Cint0(mC.MinQuality));
            oUp.SetHot((mC.IsHotPic == 1), ConvertHelper.Cint0(mC.HotWidth), ConvertHelper.Cint0(mC.HotHeight), ConvertHelper.Cint0(mC.HotQuality));

            oUp.IsWaterPic = (mC.IsWaterPic == 1);
            #endregion

            #region
            //------------------------------------------------
            bool isOk = oUp.UploadFile();
            if (!isOk)
            {
                //上传出错
                return(StringHelper.XssTextClear(oUp.GetErrMsg() + mC.Id));
            }
            #endregion

            //----------------------------------------------------------------
            #region 保存入数据库
            m_r.UploadConfig_Id = mC.Id;
            m_r.JoinName        = mC.JoinName;
            m_r.JoinId          = 0;

            m_r.UserType = mC.UserType;
            m_r.UserIp   = IpHelper.GetUserIp();
            m_r.AddDate  = DateTime.Now;
            m_r.InfoText = "";
            m_r.RndKey   = key;

            m_r.Name = oUp.NewFile;
            m_r.Path = oUp.NewPath;
            m_r.Src  = StringHelper.Left(oUp.SrcName, 90);
            m_r.Ext  = oUp.FileExt;

            m_r.Size      = oUp.GetFileSize();
            m_r.PicWidth  = oUp.NewWidth;
            m_r.PicHeight = oUp.NewHeight;

            //保存入数据库
            Add_UploadFile(m_r);
            #endregion

            //------------------------------------
            //上传成功,输出结果
            return("");
        }
Beispiel #26
0
        /// <summary>
        /// 数据保存
        /// </summary>
        /// <returns></returns>
        public override string Save()
        {
            string result = string.Empty;
            int    id     = ConvertHelper.Cint0(hidId.Text);

            try
            {
                #region 数据验证

                if (string.IsNullOrEmpty(txtName.Text.Trim()))
                {
                    return(txtName.Label + "不能为空!");
                }
                var sName = StringHelper.Left(txtName.Text, 20);
                if (InformationClassBll.GetInstence().Exist(x => x.Name == sName && x.Id != id))
                {
                    return(txtName.Label + "已存在!请重新输入!");
                }

                #endregion

                #region 赋值
                //定义是否更新其他关联表变量
                bool isUpdate    = false;
                var  oldParentId = ConvertHelper.Cint0(txtParent.Text);

                //获取实体
                var model = new InformationClass(x => x.Id == id);
                //判断是否有改变名称
                if (id > 0 && sName != model.Name)
                {
                    isUpdate = true;
                }
                //修改时间与管理员
                model.UpdateDate    = DateTime.Now;
                model.Manager_Id    = OnlineUsersBll.GetInstence().GetManagerId();
                model.Manager_CName = OnlineUsersBll.GetInstence().GetManagerCName();

                //设置名称
                model.Name = sName;
                //对应的父类id
                model.ParentId = oldParentId;
                //设置备注
                model.Notes = StringHelper.Left(txtNotes.Text, 100);

                //由于限制了编辑时不能修改父节点,所以这里只对新建记录时处理
                if (id == 0)
                {
                    //设定当前的深度与设定当前的层数级
                    if (model.ParentId == 0)
                    {
                        //设定当前的层数级
                        model.Depth = 0;
                        //父Id为0时,根Id也为0
                        model.RootId = 0;
                    }
                    else
                    {
                        //设定当前的层数
                        model.Depth = ConvertHelper.Cint0(InformationClassBll.GetInstence().GetFieldValue(ConvertHelper.Cint0(ddlParentId.SelectedValue), InformationClassTable.Depth)) + 1;
                        //获取父类的父Id
                        model.RootId = ConvertHelper.Cint0(InformationClassBll.GetInstence().GetFieldValue(model.ParentId, InformationClassTable.ParentId));
                    }

                    //限制分类层数只能为3层
                    if (model.Depth > 3)
                    {
                        return("信息分类只能创建3层分类!");
                    }
                }

                //设置排序
                model.Sort = ConvertHelper.Cint0(txtSort.Text);
                if (model.Sort == 0)
                {
                    model.Sort = InformationClassBll.GetInstence().GetSortMax(model.ParentId) + 1;
                }

                //设定当前项是否显示
                model.IsShow = ConvertHelper.StringToByte(rblIsShow.SelectedValue);
                //设定当前项是否单页
                model.IsPage = ConvertHelper.StringToByte(rblIsPage.SelectedValue);

                //SEO
                model.SeoTitle = StringHelper.Left(txtSeoTitle.Text, 100);
                model.SeoKey   = StringHelper.Left(txtSeoKey.Text, 100);
                model.SeoDesc  = StringHelper.Left(txtSeoDesc.Text, 200);
                #endregion


                #region   图片
                //上传分类大图
                if (this.fuClassImg.HasFile && this.fuClassImg.FileName.Length > 3)
                {
                    int vid = 2; //2	信息(新闻)分类图
                    //---------------------------------------------------
                    var upload = new UploadFile();
                    result = new UploadFileBll().Upload_AspNet(this.fuClassImg.PostedFile, vid, RndKey, OnlineUsersBll.GetInstence().GetManagerId(), OnlineUsersBll.GetInstence().GetManagerCName(), upload);
                    this.fuClassImg.Dispose();
                    //---------------------------------------------------
                    if (result.Length == 0)//上传成功
                    {
                        model.ClassImg = upload.Path;
                    }
                    else
                    {
                        CommonBll.WriteLog("上传出错:" + result, null);//收集异常信息
                        return("上传出错!" + result);
                    }
                }
                //如果是修改,检查用户是否重新上传过新图片,如果是删除旧的图片
                if (model.Id > 0)
                {
                    UploadFileBll.GetInstence().Upload_DiffFile(InformationClassTable.Id, InformationClassTable.ClassImg, InformationClassTable.TableName, model.Id, model.ClassImg);

                    //同步UploadFile上传表
                    UploadFileBll.GetInstence().Upload_UpdateRs(RndKey, InformationClassTable.TableName, model.Id);
                }

                #endregion


                //----------------------------------------------------------
                //存储到数据库
                InformationClassBll.GetInstence().Save(this, model);

                #region  步更新上传图片表绑定Id
                if (id == 0)
                {
                    //同步UploadFile上传表记录,绑定刚刚上传成功的文件Id为当前记录Id
                    UploadFileBll.GetInstence().Upload_UpdateRs(RndKey, InformationClassTable.TableName, model.Id);
                }

                #endregion

                //如果本次修改改变了相关名称,则同步更新其他关联表的对应名称
                if (isUpdate)
                {
                    InformationBll.GetInstence().UpdateValue_For_InformationClass_Id(this, model.Id, InformationTable.InformationClass_Name, model.Name);
                    InformationBll.GetInstence().UpdateValue_For_InformationClass_Root_Id(this, model.Id, InformationTable.InformationClass_Root_Name, model.Name);
                }
            }
            catch (Exception e)
            {
                result = "保存失败!";

                //出现异常,保存出错日志信息
                CommonBll.WriteLog(result, e);
            }

            return(result);
        }
Beispiel #27
0
 public ActionResult Them(FormCollection collection)
 {
     if (SessionManager.CheckSession(ConstantValues.SessionKeyCurrentUser))
     {
         NotifyModel thongBao = new NotifyModel();
         try
         {
             if (!string.IsNullOrEmpty(collection["save"].ToString()))
             {
                 var   user  = (NguoiDung)SessionManager.ReturnSessionObject(ConstantValues.SessionKeyCurrentUser);
                 DonVi donVi = new DonVi();
                 donVi.Ten       = collection["ten"].ToString();
                 donVi.DiaChi    = collection["diaChi"].ToString();
                 donVi.DienThoai = collection["dienThoai"].ToString();
                 donVi.Email     = collection["email"].ToString();
                 donVi.Fax       = collection["fax"].ToString();
                 //donVi.HoTenLanhDao = collection["hoTenLanhDao"].ToString();
                 //donVi.DienThoaiLanhDao = collection["dienThoaiLanhDao"].ToString();
                 //donVi.EmailLanhDao = collection["emailLanhDao"].ToString();
                 if (collection["donViTrucThuoc"].ToString() == "0")
                 {
                     donVi.IdDonViTrucThuoc = "0";
                     donVi.Cap = 1;
                 }
                 else
                 {
                     var dvTrucThuoc = xlDonVi.Doc(collection["donViTrucThuoc"].ToString());
                     donVi.IdDonViTrucThuoc = dvTrucThuoc.Id.ToString();
                     donVi.Cap = dvTrucThuoc.Cap + 1;
                 }
                 donVi.IdNguoiTao     = user.Id.ToString();
                 donVi.IdNguoiCapNhat = user.Id.ToString();
                 HttpPostedFileBase file = Request.Files["logoDonVi"];
                 if (file.FileName != null && file.FileName != "")
                 {
                     if (file.ContentLength > 0)
                     {
                         string savedFileName = "";
                         string savedFilePath = UploadFile.getFullFilePath(UploadFile.DonViDirectory, file.FileName, out savedFileName);
                         file.SaveAs(savedFilePath);
                         donVi.Logo = "/" + UploadFile.DonViDirectory + savedFileName;
                     }
                 }
                 if (xlDonVi.Ghi(donVi))
                 {
                     thongBao.TypeNotify = "alert-success";
                     thongBao.Message    = "Thêm thành công";
                 }
                 else
                 {
                     thongBao.TypeNotify = "alert-danger";
                     thongBao.Message    = "Thêm thất bại!";
                 }
             }
         }
         catch (Exception)
         {
             thongBao.TypeNotify = "alert-danger";
             thongBao.Message    = "Thêm thất bại!";
         }
         ViewBag.ThongBao = thongBao;
         var model = xlDonVi.DocDanhSachTuDonViCha(currentUser.IdDonVi, (bool)Session[ConstantValues.SessionKeyVaiTro]);
         return(View("Them", model));
     }
     if (Request.Url != null)
     {
         SessionManager.RegisterSession(ConstantValues.SessionKeyUrl, Request.Url.AbsolutePath);
     }
     return(RedirectToAction("Index", "Login"));
 }
    protected void btnUpload_Click(object sender, EventArgs e)
    {
        string filename = Path.GetFileName(fileUpload1.PostedFile.FileName);

        Stream stream = fileUpload1.PostedFile.InputStream;

        int fileSize = fileUpload1.PostedFile.ContentLength;

        string extension = Path.GetExtension(filename);
        //Write Save Logic  to file/
        BinaryReader br = new BinaryReader(stream);
        Byte[] size = br.ReadBytes((int)stream.Length);
        //SaveToFolder(stream, filename);

        //Database already here
        List<UploadFile> L = ResolveList();

        if (L.Count > 0)
        {
            //If file is Already Exist or not if exist skip this step
            bool flag;
            flag = IsFileExistOrNot(L, filename);
            if (IsFileExistOrNot(L, filename) == false)
            {
                using (ROPAEntities obj = new ROPAEntities())
                {
                    Guid G = Guid.NewGuid();
                    UploadFile upld = new UploadFile();
                    upld.GUID = G.ToString();
                    upld.FIleFor = filename;
                    upld.SurApp_Id = null;
                    upld.filecc = size;
                    obj.AddToUploadFiles(upld);
                    obj.SaveChanges();

                    L.Add(upld);
                }
                UpdateSession(L);
                BindGridviewData();
            }
        }
        else
        {
            //Not there here  first time
            using (ROPAEntities obj = new ROPAEntities())
            {
                Guid G = Guid.NewGuid();
                UploadFile upld = new UploadFile();
                upld.GUID = G.ToString();
                upld.FIleFor = filename;
                upld.filecc = size;
                obj.AddToUploadFiles(upld);
                obj.SaveChanges();
                L.Add(upld);
            }
            UpdateSession(L);
            BindGridviewData();
        }
    }
Beispiel #29
0
        public static IObservable<ApiResponse<ProfileBanner>> AccountUpdateProfileBanner(
            this AccessToken info,
            UploadFile banner,
            int? width = null,
            int? height = null,
            int? offset_left = null,
            int? offset_top = null)
        {
            var param = new ParameterCollection()
            {
                {"banner", banner},
                {"width", width},
                {"height", height},
                {"offset_left", offset_left},
                {"offset_top", offset_top}
            };

            return info
                .GetClient()
                .SetEndpoint(Endpoints.AccountUpdateProfileBanner, HttpMethod.Post)
                .SetParameters(param)
                .GetResponse()
                .ReadResponse<ProfileBanner>();
        }
Beispiel #30
0
        public ActionResult UploadResource()
        {
            if (Request.Files.Count != 1)
            {
                return(Content("Error"));
            }

            HttpPostedFileBase hpf = Request.Files[0];
            var md5  = FileHelper.ConvertToMD5(hpf.InputStream);
            var file = Files.ConditionQuery(f.Md5 == md5, null).FirstOrDefault();

            if (file == null)
            {
                var ext         = Path.GetExtension(hpf.FileName);
                var anotherName = md5 + ext;
                // upload file to CDN Server
                var uploadFile = new UploadFile {
                    Stream = hpf.InputStream, FileName = $"2019/files/{DateTime.Today.ToString("yyyyMMdd")}/{anotherName}"
                };
                var result = FileUploader.SliceUpload(uploadFile);

                if (null == result || null == result.FileUrl)
                {
                    return(Content("上传失败"));
                }

                if (ext.ToLowerInvariant() == ".doc" || ext.ToLowerInvariant() == ".docx")
                {
                    Stream docStream = null;
                    try
                    {
                        docStream = Util.ThirdParty.Aspose.WordConverter.ConvertoPdf(hpf.InputStream);
                        var docFile = new UploadFile
                        {
                            Stream   = docStream,
                            FileName = $"2019/files/{DateTime.Today.ToString("yyyyMMdd")}/{anotherName}{FileHelper.PdfExtName}"
                        };
                        var docResult = FileUploader.SliceUpload(docFile);
                        if (null == docResult || null == docResult.FileUrl || !docResult.IsSuccess)
                        {
                            return(Content("word 转pdf失败"));
                        }
                    }
                    catch { }
                    finally
                    {
                        if (docStream != null)
                        {
                            docStream.Close();
                            docStream.Dispose();
                        }
                    }
                }

                file = new Files {
                    Md5 = md5, FileName = hpf.FileName, FilePath = result.FileUrl, ExtName = ext, FileSize = hpf.ContentLength
                };
                db.FilesDal.Insert(file);
            }

            if (Request.IsAjaxRequest())
            {
                return(Json(new
                {
                    fileId = file.FileId,
                    name = file.FileName,
                    path = file.FilePath,
                    size = file.FileSize,
                    ext = file.ExtName
                }));
            }
            else
            {
                return(Content("upload ok"));
            }
        }
Beispiel #31
0
        public IHttpActionResult Post(UploadFile value)
        {
            var result = objUploadFileRepository.Save(value);

            return(Ok(result));
        }
Beispiel #32
0
 /// <summary>
 /// Remote upload file
 /// </summary>
 /// <param name="remoteOption">Remote options</param>
 /// <param name="fileOption">File option</param>
 /// <param name="fileBytes">File bytes</param>
 /// <param name="parameters">Parameters</param>
 /// <returns>Return upload result</returns>
 public static async Task <UploadResult> RemoteUploadAsync(RemoteServerOptions remoteOption, UploadFile fileOption, byte[] fileBytes, object parameters = null)
 {
     return(await RemoteUploadAsync(remoteOption, fileOption, fileBytes, parameters).ConfigureAwait(false));
 }
Beispiel #33
0
 public Task Update(UploadFile file)
 {
     return(this.repository.Update(file));
 }
Beispiel #34
0
 /// <summary>
 ///  Local upload file
 /// </summary>
 /// <param name="uploadOption">Upload option</param>
 /// <param name="fileOption">File option</param>
 /// <param name="fileBytes">File</param>
 /// <returns>Return upload result</returns>
 public static async Task <UploadResult> LocalUploadAsync(UploadOptions uploadOption, UploadFile fileOption, byte[] fileBytes)
 {
     return(await LocalUploadAsync(uploadOption, fileOption, fileBytes).ConfigureAwait(false));
 }
        public async Task <IActionResult> OnPostAsync()
        {
            string username = HttpContext.Session.GetString("username");
            User   user     = await _context.User.FirstOrDefaultAsync(u => u.UserName.Equals(username));

            AppCondition app = await _context.AppCondition.FirstOrDefaultAsync(app => app.AppConditionId.Equals(1));

            Team = await _context.Team.FirstOrDefaultAsync(t => t.UserID.Equals(user.UserId) && t.EventID.Equals(app.EventID));

            //The team won't be null because of test performed earlier
            if ((UploadFile == null) || (UploadFile.Length == 0))
            {
                Message = "Please select a file first to upload!!";
                return(Page());
            }

            //Before we store the file we need to get rid of the previous file if any
            TeamPresentation teamPresentation1 = await _context.TeamPresentation.FirstOrDefaultAsync(tp => tp.TeamID.Equals(Team.TeamId) && tp.EventID.Equals(app.EventID));

            if (teamPresentation1 != null)
            {
                //That means team leader has already upload a file before this
                //So we need to start by deleting that file first
                string storedFile = teamPresentation1.FileName;
                var    oldPath    = Path.Combine(Directory.GetCurrentDirectory(), "Files", storedFile);
                if (System.IO.File.Exists(oldPath))
                {
                    System.IO.File.Delete(oldPath);
                    _context.TeamPresentation.Remove(teamPresentation1);
                    await _context.SaveChangesAsync();

                    Message = "Your previous file has been deleted!!";
                }
                else
                {
                }
            }

            string extension = Path.GetExtension(UploadFile.FileName);
            //Since team name is unique for an event and username is unique always
            string fileName = Team.JoinCode + username + Team.TeamId + extension;

            var path = Path.Combine(
                Directory.GetCurrentDirectory(), "Files", fileName);

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

            Message = "You file has been uploaded!!";

            TeamPresentation teamPresentation = new TeamPresentation()
            {
                TeamID   = Team.TeamId,
                EventID  = Team.EventID,
                FileName = fileName,
                TeamName = Team.TeamName,
            };

            _context.TeamPresentation.Add(teamPresentation);
            await _context.SaveChangesAsync();

            return(RedirectToPage("./MyTeam"));
        }
 private string getFileInfo( UploadFile f )
 {
     if (f.FileType == (int)FileType.Pic)
         return string.Format( "<a href='{0}'><img src='{1}' /></a>", f.FullPath, f.FullThumbPath );
     return string.Format( "<a href='{0}'>{0}</a>", f.FullPath );
 }
Beispiel #37
0
        private void item_OffLineFilesButtonClick(object sender, EventArgs e)
        {
            FileTransfersItem item = sender as FileTransfersItem;
            SendFileManager sendFileManager = item.Tag as SendFileManager;
            this.AppendSystemRtf(string.Format("文件 {0} 取消发送成功。", sendFileManager.Name));
            if (OnLine)
            {
                udpSendFile.CancelSend(sendFileManager.MD5);
            }

            Util.SendFileManagerList.Add(sendFileManager.MD5, sendFileManager);
            FTPClient ftpClient = new FTPClient(Util.ServerAddress,Util.ftpPath, Util.ftpUser, Util.ftpPswd, Util.ftpPort);
            ftpClient.sendFileManager = sendFileManager;
            sendFileManager.ftpClient = ftpClient;
            item.Tag = sendFileManager;
            item.Style = FileTransfersItemStyle.Cancel;
            this.AppendSystemRtf(string.Format("文件 {0} 更改发送离线文件。",sendFileManager.Name));
            UploadFile ftpPush = new UploadFile(this);
            Thread pushThread = new Thread(ftpPush.PushFile);
            pushThread.Start(ftpClient);
        }
Beispiel #38
0
        public static IObservable<ApiResponse<Status>> StatusesUpdateWithMedia(
            this AccessToken info,
            string status,
            UploadFile[] media,
            bool? possiblySensitive = null,
            long? inReplyToStatusId = null,
            double? latitude = null,
            double? longitude = null,
            string placeId = null,
            bool? displayCoordinates = null)
        {
            var param = new ParameterCollection()
            {
                {"status", status},
                {"possibly_sensitive", possiblySensitive},
                {"in_reply_to_status_id", inReplyToStatusId},
                {"lat", latitude},
                {"long", longitude},
                {"place_id", placeId},
                {"display_coordinates", displayCoordinates}
            };

            foreach (var m in media)
            {
                param.Add(new Parameter("media[]", m.Data, m.FileName));
            }

            return info
                .GetClient()
                .SetEndpoint(Endpoints.StatusesUpdateWithMedia, HttpMethod.Post, ContentType.MultipartFormData)
                .SetParameters(param)
                .GetResponse()
                .ReadResponse<Status>();
        }
Beispiel #39
0
        /// <summary>
        /// ファイルを上書きアップロードします。
        /// </summary>
        /// <param name="fileId">上書きするファイルの ID。</param>
        /// <param name="file">アップロードするファイルの情報。</param>
        /// <param name="share">true (アップロードしたファイルを共有する場合)、false (それ以外の場合)。</param>
        /// <param name="message">通知メールに含めるメッセージ。</param>
        /// <param name="emails">共有ファイルの情報を通知するユーザのメールアドレスの配列。</param>
        /// <returns>アップロードしたファイルの情報。</returns>
        public UploadedFile Overwrite(long fileId, UploadFile file, bool share, string message, string[] emails)
        {
            var result = OverwriteFunction.Execute(AuthToken, fileId, file, share, message, emails);

            if (result.Status != "upload_ok") HandleErrorStatus(result.Status);

            return result.Files[0];
        }
    /// <summary>
    /// Attempts to upload a single file a Tableau Server, and then make it a published workbook
    /// </summary>
    /// <param name="localFilePath"></param>
    /// <returns></returns>
    private bool AttemptUploadSingleFile_Inner(
        string localFilePath, 
        string projectId, 
        CredentialManager.Credential dbCredentials)
    {
        string uploadSessionId;
        try
        {
            var fileUploader = new UploadFile(_onlineUrls, _onlineSession, localFilePath, _uploadChunkSizeBytes, _uploadChunkDelaySeconds);
            uploadSessionId = fileUploader.ExecuteRequest();
        }
        catch (Exception exFileUpload)
        {
            this.StatusLog.AddError("Unexpected error attempting to upload file " + localFilePath + ", " + exFileUpload.Message);
            throw exFileUpload;
        }

        this.StatusLog.AddStatus("File chunks upload successful. Next step, make it a published workbook", -10);
        try
        {
            string fileName = Path.GetFileNameWithoutExtension(localFilePath);
            string uploadType = RemoveFileExtensionDot(Path.GetExtension(localFilePath).ToLower());
            var workbook = FinalizePublish(uploadSessionId, fileName, uploadType, projectId, dbCredentials);
            StatusLog.AddStatus("Upload content details: " + workbook.ToString(), -10);
            StatusLog.AddStatus("Success! Uploaded workbook " + Path.GetFileName(localFilePath));
        }
        catch (Exception exPublishFinalize)
        {
            this.StatusLog.AddError("Unexpected error finalizing publish of file " + localFilePath + ", " + exPublishFinalize.Message);
            LogManualAction_UploadWorkbook(localFilePath);
            throw exPublishFinalize;
        }
        return true;     //Success
    }
Beispiel #41
0
        protected void Upload(UploadFile PostedFile,
                              UploadResponseMessage response, string filePath)
        {
            string FileName = string.Empty;

            try
            {
                BCCityAdmin cityContent   = new BCCityAdmin();
                DateTime    cityStartDate = new DateTime();
                DataTable   _dtTrkpts     = new DataTable();
                DataTable   studInfo      = null;
                FileName = PostedFile.FileName;
                string NewFile     = "";
                string NewFileName = "";
                string FilePath    = string.Empty;


                studInfo = objStudent.GetMyProfileInfo(studentId);
                schoolId = Convert.ToInt32(studInfo.Rows[0]["SchoolId"]);
                classId  = Convert.ToInt32(studInfo.Rows[0]["ClassId"]);

                FilePath = filePath + schoolId + @"\" +
                           classId + @"\" + studentId.ToString() + @"\".ToString();


                System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(FilePath);
                if (!(dir.Exists))
                {
                    System.IO.Directory.CreateDirectory(FilePath);
                }
                //string extension = System.IO.Path.GetExtension(FileName).ToLower();
                string[] extention = FileName.Split('.');
                if (extention != null && extention.Count() > 0)
                {
                    FileName = extention[0];
                }

                //if ((extension == ".gpx") | (extension == ".GPX"))
                //{
                if (IsFileUploaded(FilePath + FileName + ".xml"))
                {
                    ErrorLogManager.WriteLog(response, FileName, "008", "File already uploaded!");
                }
                else
                {
                    #region Save file on server for evaluation

                    File.WriteAllBytes(FilePath + FileName + ".xml", PostedFile.FileData);
                    DataTable dt = cityContent.GetCityContent(Convert.ToInt32(studInfo.Rows[0]["CityId"]), 0);

                    try
                    {
                        string TimeStamp = DateTime.Now.Day.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Year.ToString() +
                                           DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString() + "";

                        NewFileName = UserRoleId.ToString() + "_" + UserId.ToString() + "_" + TimeStamp + ".xml";
                        File.Move(FilePath + FileName + ".xml", FilePath + NewFileName); // Try to move
                        NewFile = FilePath + NewFileName;
                    }
                    catch (IOException ex)
                    {
                        NewFile     = FilePath + FileName;
                        NewFileName = FileName;
                    }

                    //File.WriteAllBytes(FilePath + FileName + ".xml", PostedFile.FileData);
                    ////fu_UploadGpx.SaveAs(FilePath + FileName.Replace(".gpx", ".xml"));
                    //DataTable dt = cityContent.GetCityContent(cityId, 0);
                    //XElement root = null;
                    //DateTime DateOfFile = new DateTime();
                    //try
                    //{
                    //    root = XElement.Load(FilePath + FileName + ".xml");
                    //    DateOfFile = DateTime.Parse(root.Elements().Skip(1).Take(1).Elements().Take(1).ToList()[0].Value);
                    //}
                    //catch (Exception ex)
                    //{
                    //    ErrorLogManager.WriteLog(response,FileName, "009", "Uploaded File does not have Time Information, Please check the file and re-upload");
                    //    return;
                    //}
                    //if (dt != null && dt.Rows.Count > 0)
                    //{
                    //    cityStartDate = (dt.Rows[0]["CityStartDate"] != DBNull.Value ? Convert.ToDateTime(dt.Rows[0]["CityStartDate"]) : new DateTime());

                    //    if (cityStartDate != new DateTime() &&
                    //        DateOfFile != new DateTime() &&
                    //        DateOfFile.Date <= cityStartDate.Date)
                    //    {
                    //        ErrorLogManager.WriteLog(response,FileName, "010", "File can not be uploaded prior to Batch Start Date.");
                    //        return;
                    //    }
                    //}
                    //try
                    //{
                    //    string TimeStamp = DateTime.Now.Day.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Year.ToString() +
                    //    DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString() + "";

                    //    NewFileName = UserRoleId.ToString() + "_" + UserId.ToString() + "_" + TimeStamp + ".xml";
                    //    File.Move(FilePath + FileName + ".xml", FilePath + NewFileName); // Try to move
                    //    NewFile = FilePath + NewFileName;
                    //}
                    //catch (IOException ex)
                    //{
                    //    NewFile = FilePath + FileName + ".xml";
                    //    NewFileName = FileName;
                    //}

                    #endregion

                    DataTable dtNew = new DataTable();
                    dtNew = LoadGPXWaypoints(NewFile);
                    DateTime DateOfFile = DateTime.MinValue;;
                    if (dt != null && dt.Rows.Count > 0 && dtNew != null && dtNew.Rows.Count > 0)
                    {
                        cityStartDate = Convert.ToDateTime(dt.Rows[0]["CityStartDate"]);
                        DateOfFile    = Convert.ToDateTime(dtNew.Rows[0]["time"]);
                    }

                    if ((cityStartDate != new DateTime() &&
                         DateOfFile <= cityStartDate) ||
                        (DateOfFile < DateTime.Parse(ConfigurationManager.AppSettings["BatchStartDate"])))
                    {
                        ErrorLogManager.WriteLog(response, FileName, "010", "File can not be uploaded prior to Batch Start Date.");
                        return;
                    }

                    _dtTrkpts = dtNew;
                    int    trackCount   = dtNew.Rows.Count; //(dtNew.Rows.Count / 5) + 1;
                    double highestSpeed = 0;

                    DataTable dtNewRows = CheckPreviousGPXTrackPointsNew(UserId,
                                                                         schoolId,
                                                                         classId, dtNew);

                    if (dtNewRows != null &&
                        dtNewRows.Rows.Count > 0)
                    {
                        double distance = CalculateTotalDistance(dtNewRows);
                        double time     = CalculateTotalTime(dtNewRows);
                        double timeAvg  = CalculateAvgTime(dtNewRows);

                        #region Calculate Average Speed

                        if (timeAvg > 0)
                        {
                            time = timeAvg;
                        }

                        double avgSpeed = 0.0;
                        if (time > 0)
                        {
                            avgSpeed = distance / time;
                        }

                        #endregion

                        int speedLimit = 15;

                        if (ConfigurationManager.AppSettings["SpeedLimit"].ToString() != "")
                        {
                            speedLimit = Convert.ToInt32(ConfigurationManager.AppSettings["SpeedLimit"]);
                        }

                        if (avgSpeed == 0)
                        {
                            ErrorLogManager.WriteLog(response, FileName, "011", "Invalid file!");
                            File.Delete(NewFile);
                        }
                        else
                        {
                            highestSpeed = GetHighestSpeedInGPX(dtNewRows);

                            #region Check ongoing stage information

                            int     stagePlanId   = 0;
                            double  stageDistance = 0;
                            double  distCovered   = 0;
                            DataSet _dtStage      = objStudent.GetCurrentStageInfo((studentId > 0 ? studentId : UserId),
                                                                                   UserRoleId, classId);
                            if (_dtStage.Tables[0].Rows.Count > 0)
                            {
                                stagePlanId   = Convert.ToInt32(_dtStage.Tables[0].Rows[0]["StagePlanId"]);
                                stageDistance = Convert.ToDouble(_dtStage.Tables[0].Rows[0]["Distance"]);
                                distCovered   = double.Parse(_dtStage.Tables[0].Rows[0]["Distance_Covered"].ToString(), System.Globalization.CultureInfo.InvariantCulture);
                                //Convert.ToDouble(_dtStage.Tables[0].Rows[0]["Distance_Covered"]);
                            }

                            #endregion
                            //if (avgSpeed > speedLimit)
                            //{
                            //    ErrorLogManager.WriteLog(response, FileName, "016", "Speed Limit Crossed!");
                            //}
                            //else
                            if (avgSpeed <= speedLimit && highestSpeed <= speedLimit)
                            {
                                //Save data in Student Uploads

                                #region Save data in Student Uploads

                                // Check for similar track points


                                int res = objStudent.StudentsUpload(
                                    UserRoleId, UserId,
                                    0, studentId,
                                    stagePlanId, stageDistance, distCovered, (NewFile), NewFileName,
                                    DateTime.Now, distance, time, classId, 1, trackCount);
                                if (res > 0)
                                {
                                    _SaveTrackPoints(_dtTrkpts, res);
                                    ErrorLogManager.WriteLog(response, FileName, "012", "File uploaded successfully!", false);
                                }
                                else
                                {
                                    ErrorLogManager.WriteLog(response, FileName, "008", "File already uploaded!");
                                    File.Delete(NewFile);
                                }

                                #endregion
                            }
                            else // Upload file out of speed limit. No change in stage distance.
                            {
                                #region Save data in Student Uploads
                                int res = objStudent.StudentsUploadExtraSpeed(
                                    UserRoleId, UserId,
                                    0,
                                    studentId, stagePlanId,
                                    stageDistance, distCovered, (NewFile), NewFileName,
                                    DateTime.Now, distance, time, classId, 0, trackCount);
                                if (res > 0)
                                {
                                    _SaveTrackPoints(_dtTrkpts, res);
                                    #region Send email to Class Admin & City Admin for speed limit

                                    if (avgSpeed > speedLimit || highestSpeed > speedLimit)
                                    {
                                        try
                                        {
                                            string ClassAdminEmail = studInfo.Rows[0]["ClassAdminEmail"].ToString();
                                            string CityAdminEmail  = studInfo.Rows[0]["CityAdminEmail"].ToString();

                                            StringBuilder sb = new StringBuilder();
                                            sb.Append("<p>Dear " + studInfo.Rows[0]["ClassAdminName"].ToString() + ",</p>");
                                            sb.Append("<p><b>" + UserName + " (Student in " + studInfo.Rows[0]["School"].ToString() + ", " + studInfo.Rows[0]["Class"].ToString() + ")</b> have uploaded a GPX file (" + NewFileName + ") with speed <b>" + avgSpeed.ToString() + " Kmph and heighest speed being " + highestSpeed + "</b>.</p>");
                                            sb.Append("<p>Kindly approve or reject file manually.</p>");
                                            Helper.sendMailMoreThanAvgSpeed("BikeTour - Speed Limit Crossed!", ClassAdminEmail, sb.ToString());

                                            StringBuilder sb2 = new StringBuilder();
                                            sb2.Append("<p>Dear " + studInfo.Rows[0]["CityAdminName"].ToString() + ",</p>");
                                            sb.Append("<p><b>" + UserName + " (Student in " + studInfo.Rows[0]["School"].ToString() + ", " + studInfo.Rows[0]["Class"].ToString() + ")</b> have uploaded a GPX file (" + NewFileName + ") with speed <b>" + avgSpeed.ToString() + "Kmph and heighest speed being " + highestSpeed + "</b>.</p>");
                                            sb.Append("<p>Kindly approve or reject file manually.</p>");
                                            Helper.sendMailMoreThanAvgSpeed("BikeTour - Speed Limit Crossed!", ClassAdminEmail, sb2.ToString());
                                        }
                                        catch (Exception ex)
                                        {
                                        }
                                    }

                                    #endregion
                                    ErrorLogManager.WriteLog(response, FileName, "012", "File uploaded successfully!", false);
                                }
                                else
                                {
                                    ErrorLogManager.WriteLog(response, FileName, "008", "File already uploaded!");
                                    File.Delete(NewFile);
                                }

                                #endregion
                            }
                        }
                    }
                    else
                    {
                        ErrorLogManager.WriteLog(response, FileName, "008", "File already uploaded!");
                    }
                }
            }
            catch (Exception ex)
            {
                ErrorLogManager.WriteLog(response, FileName, "013", "Select GPX file!" + ex.Message);
            }
        }
Beispiel #42
0
 public static string GetDoiRegResult(String fileName, String userName, String password)
 {
     StringBuilder sb = new StringBuilder();
     UploadFile uploadFile = new UploadFile();
     DoiRegResult result = uploadFile.getDoiRegResult(fileName, userName, password);
     return result.state;
 }
Beispiel #43
0
        private void button1_Click(object sender, EventArgs e)
        {
            vk start = new vk();
            if (checkBox1.Checked) // если флажон для статуса
            {
                SetStatus setStatus = new SetStatus(start.setStatus);
                IAsyncResult res1 = setStatus.BeginInvoke(richTextBox1.Text, null, null);
                res1.AsyncWaitHandle.WaitOne(2000);
                if (setStatus.EndInvoke(res1).IndexOf("error") != -1)
                {
                    NotifyEvent ShowNotify = new NotifyEvent(ShowNotifyWindow);
                    this.Invoke(ShowNotify, "Ошибка!", "При публикации\nвозникли проблемы!", (uint)0);
                }
                //start.setStatus(richTextBox1.Text);
            }
            else // если для записи на стене
            {
                string name = "";

                if (checkBox2.Checked) // если нужно изображение, загружаем
                {
                    OpenFileDialog open = new OpenFileDialog();
                    open.FileName = "";
                    open.Filter = "Изображения|*.jpg;*.gif;*.png";

                    if (open.ShowDialog() == DialogResult.OK)
                    {
                        UploadFile upload = new UploadFile(start.UploadFile);
                        IAsyncResult res11 = upload.BeginInvoke(ID, open.FileName, null, null);

                        int iter = 0;

                        while (!res11.IsCompleted)
                        {
                            iter++;
                            if (iter == 500)
                            {
                                iter = 0;
                                Application.DoEvents();
                            }
                        }

                        res11.AsyncWaitHandle.WaitOne();

                        name = upload.EndInvoke(res11);
                    }

                    if (name == "")
                    {
                        NotifyEvent ShowNotify = new NotifyEvent(ShowNotifyWindow);
                        this.Invoke(ShowNotify, "Ошибка!", "При публикации\nвозникли проблемы!", (uint)0);
                    }
                }

                if (ID != 0) // не себе
                {
                    if (name != "")
                    {
                        SetWallStatus setWallStatus = new SetWallStatus(start.SetWallStatus);
                        IAsyncResult res1 = setWallStatus.BeginInvoke(richTextBox1.Text, name, ID, null, null);
                        res1.AsyncWaitHandle.WaitOne(2000);
                        if (setWallStatus.EndInvoke(res1).IndexOf("error") != -1)
                        {
                            NotifyEvent ShowNotify = new NotifyEvent(ShowNotifyWindow);
                            this.Invoke(ShowNotify, "Ошибка!", "При публикации\nвозникли проблемы!", (uint)0);
                        }
                        //start.SetWallStatus(richTextBox1.Text, name, ID);
                    }
                    else
                    {
                        SetWallStatus setWallStatus = new SetWallStatus(start.SetWallStatus);
                        IAsyncResult res1 = setWallStatus.BeginInvoke(richTextBox1.Text, "", ID, null, null);
                        res1.AsyncWaitHandle.WaitOne(2000);
                        if (setWallStatus.EndInvoke(res1).IndexOf("error") != -1)
                        {
                            NotifyEvent ShowNotify = new NotifyEvent(ShowNotifyWindow);
                            this.Invoke(ShowNotify, "Ошибка!", "При публикации\nвозникли проблемы!", (uint)0);
                        }
                        //start.SetWallStatus(richTextBox1.Text, "", ID);
                    }
                }
                else // себе
                {
                    if (name != "")
                    {
                        SetWallStatus setWallStatus = new SetWallStatus(start.SetWallStatus);
                        IAsyncResult res1 = setWallStatus.BeginInvoke(richTextBox1.Text, name, ID, null, null);
                        res1.AsyncWaitHandle.WaitOne(2000);
                        if (setWallStatus.EndInvoke(res1).IndexOf("error") != -1)
                        {
                            NotifyEvent ShowNotify = new NotifyEvent(ShowNotifyWindow);
                            this.Invoke(ShowNotify, "Ошибка!", "При публикации\nвозникли проблемы!", (uint)0);
                        }
                        //start.SetWallStatus(richTextBox1.Text, name, ID);
                    }
                    else
                    {
                        SetStatus setWallStatus = new SetStatus(start.SetWallStatus);
                        IAsyncResult res1 = setWallStatus.BeginInvoke(richTextBox1.Text, null, null);
                        res1.AsyncWaitHandle.WaitOne(2000);
                        if (setWallStatus.EndInvoke(res1).IndexOf("error") != -1)
                        {
                            NotifyEvent ShowNotify = new NotifyEvent(ShowNotifyWindow);
                            this.Invoke(ShowNotify, "Ошибка!", "При публикации\nвозникли проблемы!", (uint)0);
                        }
                        //start.SetWallStatus(richTextBox1.Text);
                    }
                }
            }
            this.Close();
        }
        public void SaveEditorPic() {

            if (ctx.HasUploadFiles == false) {
                echoError( "不能上传空图片" );
                return;
            }

            HttpFile file = ctx.GetFileSingle();
            Result result = Uploader.SaveImg( file );
            string savedPath = result.Info.ToString();

            UploadFile f = new UploadFile();
            f.Name = file.FileName;
            f.Path = savedPath;
            f.FileType = (int)FileType.Pic;
            f.insert();

            Dictionary<String, String> dic = new Dictionary<String, String>();
            dic.Add( "url", f.PicO ); // 图片的完整url
            dic.Add( "title", f.Name ); // 图片名称
            dic.Add( "original", ctx.GetFileSingle().FileName ); // 图片原始名称
            dic.Add( "state", "SUCCESS" ); // 上传成功

            echoJson( dic );
        }
Beispiel #45
0
        private void UploadButton_Click(object sender, RoutedEventArgs e)
        {
            System.Windows.Forms.OpenFileDialog openFileDialog = new System.Windows.Forms.OpenFileDialog();
            if (openFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                String token = CacheService.Instance.GetStuToken();

                FileResult fr = rf.UploadFile(openFileDialog.FileName, token);

                //获取文件名字
                String file_name = openFileDialog.FileName.Split('\\')[openFileDialog.FileName.Split('\\').Length - 1];

                if (fr != null)
                {
                    if (fr.code == "200")
                    {
                        //关联文件与记录
                        List <Attach> attaches = new List <Attach>();
                        foreach (Student s in CacheService.Instance.GetStudentList())
                        {
                            Attach a = new Attach {
                                subjectId = s.RecordId, ownerId = s.Id, type = "EXPERIMENT_RECORD_FILE"
                            };
                            attaches.Add(a);
                        }

                        AttachResult ar = rf.AttachRecordWithFile(CacheService.Instance.ExperimentId, fr.data.id, attaches, CacheService.Instance.GetStuToken());

                        if (ar != null)
                        {
                            if (ar.code == "200")
                            {
                                UploadFile up = new UploadFile()
                                {
                                    FileName = file_name, FileType = UploadFile.EXPERIMENT, Status = UploadFile.SUCCESS, FilePath = openFileDialog.FileName, Id = fr.data.id, Color = "#FF979797", Operation = UploadFile.OPENDOC
                                };
                                upfiles.Add(up);
                                fileList.Items.Refresh();
                            }
                            else
                            {
                                LSMessageBox.Show("关联文件错误", ar.message);
                                UploadFile up = new UploadFile()
                                {
                                    FileName = file_name, FileType = UploadFile.EXPERIMENT, Status = UploadFile.FAIL, FilePath = openFileDialog.FileName, Id = -1, Color = "Red", Operation = UploadFile.REUPLOAD
                                };
                                upfiles.Add(up);
                                fileList.Items.Refresh();
                            }
                        }
                        else
                        {
                            LSMessageBox.Show("网络错误", "网络异常");
                            UploadFile up = new UploadFile()
                            {
                                FileName = file_name, FileType = UploadFile.EXPERIMENT, Status = UploadFile.FAIL, FilePath = openFileDialog.FileName, Id = -1, Color = "Red", Operation = UploadFile.REUPLOAD
                            };
                            upfiles.Add(up);
                            fileList.Items.Refresh();
                        }
                    }
                    else
                    {
                        LSMessageBox.Show("上传文件错误", fr.message);
                        UploadFile up = new UploadFile()
                        {
                            FileName = file_name, FileType = UploadFile.EXPERIMENT, Status = UploadFile.FAIL, FilePath = openFileDialog.FileName, Id = -1, Color = "Red", Operation = UploadFile.REUPLOAD
                        };
                        upfiles.Add(up);
                        fileList.Items.Refresh();
                    }
                }
                else
                {
                    LSMessageBox.Show("网络错误", "网络异常");
                    UploadFile up = new UploadFile()
                    {
                        FileName = file_name, FileType = UploadFile.EXPERIMENT, Status = UploadFile.FAIL, FilePath = openFileDialog.FileName, Id = -1, Color = "Red", Operation = UploadFile.REUPLOAD
                    };
                    upfiles.Add(up);
                    fileList.Items.Refresh();
                }
            }
        }
Beispiel #46
0
 public override void OnResponse(BinaryReader reader)
 {
     file = TLObject.Read <UploadFile>(reader);
 }
Beispiel #47
0
        public static string uploadForString(string methodOrUri, YopRequest request)
        {
            string serverUrl = richRequest(HttpMethodType.POST, methodOrUri, request);

            //NameValueCollection original = request.getParams();
            //NameValueCollection alternate = new NameValueCollection();
            List <string> uploadFiles = request.getParam("fileURI");

            if (null == uploadFiles || uploadFiles.Count == 0)
            {
                throw new SystemException("上传文件时参数_file不能为空!");
            }

            List <UploadFile> upfiles = new List <UploadFile>();

            foreach (string strPath in uploadFiles)
            {
                UploadFile files = new UploadFile();
                files.Name     = "_file";
                files.Filename = Path.GetFileName(strPath);

                Stream oStream  = File.OpenRead(strPath.Split(':')[1]);
                byte[] arrBytes = new byte[oStream.Length];
                int    offset   = 0;
                while (offset < arrBytes.LongLength)
                {
                    offset += oStream.Read(arrBytes, offset, arrBytes.Length - offset);
                }
                files.Data = arrBytes;
                upfiles.Add(files);
            }

            signAndEncrypt(request);
            request.setAbsoluteURL(serverUrl);
            request.encoding("blowfish");

            Stream stream  = HttpUtils.PostFile(request, upfiles).GetResponseStream();
            string content = new StreamReader(stream, Encoding.UTF8).ReadToEnd();

            return(content);


            //foreach(string uploadFile in uploadFiles)
            //{
            //  try
            //  {
            //    alternate.Add("fileURI", new UrlResource(new URI(uploadFile)));

            //  }
            //  catch (Exception e)
            //  {
            //    System.Diagnostics.Debug.WriteLine("_file upload error.", e);
            //  }
            //}

            //signAndEncrypt(request);
            //request.setAbsoluteURL(serverUrl);
            //request.encoding();

            //foreach (string key in original.AllKeys)
            //{
            //  //alternate.put(key, new ArrayList<Object>(original.get(key)));
            //  alternate.Add(key, original.Get(key));
            //}

            ////string content = getRestTemplate(request).postForObject(serverUrl, alternate, String.class);
            ////  //if (logger.isDebugEnabled()) {
            ////  //    logger.debug("response:\n" + content);
            ////  //}
            ////  return content;
            //return null;
        }
Beispiel #48
0
 private void UploadForm_Load(object sender, EventArgs e)
 {
     this.msg       = new MSG();
     this.cutUpload = new UploadFile();
 }
Beispiel #49
0
        public async Task <ActionResult> Upload(UploadFile request)
        {
            var response = await _mediator.Send(request);

            return(Content(response, "text/plain"));
        }
Beispiel #50
0
        public async Task <int> PostProductImage(List <IFormFile> PictureContentI, int ProductId)
        {
            int ret = 0;  // 12.系統回傳0。

            try
            {
                string FilePath = Path.Combine(_environment.WebRootPath, @"images");
                // 8.系統接收6上傳資料。
                //string FileName = "";
                //byte[] PContent = null;
                //string PictureType = "";
                List <UploadFile> lstUF = new List <UploadFile>();
                UploadFile        UF;
                if (HttpContext.Request.HasFormContentType)
                {
                    //// 取得Client傳送之表單內容
                    //IFormCollection form;
                    ////form = HttpContext.Request.Form; // syncmbc
                    //// Or
                    //form = await HttpContext.Request.ReadFormAsync(); // async
                    int o = 0;
                    foreach (var item in PictureContentI)
                    {
                        o              += 1;
                        UF              = new UploadFile();
                        UF.ProductId    = ProductId;
                        UF.FileName     = item.FileName;
                        UF.FileName     = Path.GetFileName(UF.FileName);
                        UF.DisplayOrder = o;
                        if (UF.FileName.Length > 50)
                        {
                            UF.FileName = UF.FileName.Substring(UF.FileName.Length - 50);
                        }
                        // 8-1.系統在Post Action【Import/ReportPost】將上傳.xlsx儲存至~/xlsx資料夾。
                        var fileName     = item.FileName.Substring(item.FileName.LastIndexOf(@"\") + 1);
                        var FilePathTrue = Path.Combine(FilePath, fileName);
                        using (Image img = Image.FromStream(item.OpenReadStream()))
                        {
                            //img.Resize(1280, 960).Save(FilePathTrue);
                            img.Save(FilePathTrue);
                        }
                        using (Image img = Image.FromFile(FilePathTrue))
                        {
                            UF.PictureContent = img.ToByteArray();
                        }
                        UF.PictureType = item.ContentType;
                        lstUF.Add(UF);
                        System.IO.File.Delete(FilePathTrue);
                    }
                }
                // 9.系統新增多筆商品分類資料。
                if (lstUF.Count > 0)
                {
                    ret = await IAR.InsertProductImageMulti(lstUF);
                }
                // 10.系統判斷9成功執行。
                // 11.系統回傳9傳回值。
            }
            catch (Exception ex)
            {
                string msg = ex.Message;
                // 10.系統判斷9執行時發生例外。
                //  10a-1.系統回傳3。
                ret = 3;
            }
            return(ret);
        }
Beispiel #51
0
 public UploadFileResult UploadFile(UploadFile file)
 {
     UploadFileResult rst = new UploadFileResult();
     try
     {
         string path;
         if (file.isUpdate)
             path = System.Environment.CurrentDirectory + "\\" + file.UpdateType + "\\" + file.FilePath;
         else
             path = file.FilePath;
         if (!Directory.Exists(path))
             Directory.CreateDirectory(path);
         using (FileStream outputStream = new FileStream(path+"\\"+file.FileName, FileMode.OpenOrCreate, FileAccess.Write))
         {
             file.FileStream.CopyTo(outputStream);
             outputStream.Flush();
         }
         rst.IsSuccess = true;
     }
     catch(Exception e)
     {
         rst.IsSuccess = false;
         rst.Message = e.Message;
     }
     return rst;
 }
Beispiel #52
0
        public async Task <IActionResult> Settings(UserSettingsViewModel model)
        {
            ViewData["Error1"] = true;
            if (!ModelState.IsValid)
            {
                return(View(model));
            }
            var loginUserName = User.Identity.Name;

            if (loginUserName == null)
            {
                return(RedirectToAction("Login", "Account", new { ReturnUrl = "/User/Setting" }));
            }

            var user = await _userRepo.FindAsync(p => p.UserId == model.UserId);

            if (user == null)
            {
                throw new Exception("用户找不到,或已被删除");
            }
            if (user.Name != loginUserName)
            {
                return(RedirectToAction("Index", "Home"));
            }

            var nameIsExist = await _userRepo.IsExistAsync(p => p.Name == model.Name);

            if (nameIsExist && (model.Name != user.Name))
            {
                ModelState.AddModelError("", "此名称已存在");
                return(View(model));
            }
            var emailIsExist = await _userRepo.IsExistAsync(p => p.Email == model.Email);

            if (emailIsExist && model.Email != user.Email)
            {
                ModelState.AddModelError("", "此邮箱地址已存在");
                return(View(model));
            }

            if (model.AvatarFile != null)
            {
                string fileExtensions = string.Empty;
                try
                {
                    var fileNameSplit = model.AvatarFile.FileName.Split('.');
                    fileExtensions = fileNameSplit[fileNameSplit.Length - 1];
                }
                catch (IndexOutOfRangeException)
                {
                    ModelState.AddModelError("", "未知文件格式");
                    return(View(model));
                }
                if (fileExtensions.ToLower() != "jpg" && fileExtensions.ToLower() != "png")
                {
                    ModelState.AddModelError("", "请上传 .JPG 或者 .PNG 格式的图片");
                    return(View(model));
                }
                var fileName   = new StringBuilder().AppendFormat($"{model.UserId}_{model.Name}.{fileExtensions}").ToString();
                var uploadFile = new UploadFile(env);
                model.Avatar = await uploadFile.UploadImage(model.AvatarFile, fileName);
            }

            user.Name  = model.Name;
            user.Email = model.Email;
            if (!string.IsNullOrEmpty(model.Avatar))
            {
                user.Avatar = model.Avatar;
            }
            user.Signature = model.Signature;
            var success = await _userRepo.UpdateAsync(user);

            if (success)
            {
                return(new RedirectResult(Url.Content("/User/Settings/")));
            }
            else
            {
                ModelState.AddModelError("", "保存失败,请稍后重试");
                return(View(model));
            }
        }
Beispiel #53
0
 //获取DOI注册结果
 public static string GetDoiRegResult(String fileName, String userName, String password, String RegResultSavePath)
 {
     StringBuilder sb = new StringBuilder();
     UploadFile uploadFile = new UploadFile();
     DoiRegResult result = uploadFile.getDoiRegResult(fileName, userName, password);
     //保存注册结果
     if (result.state == "已完成")
     {
         XElement root = XElement.Load(result.resultFileUrl.Replace("Successful.log", ""), LoadOptions.SetLineInfo);//加载XML文档
         root.Save(RegResultSavePath);
     }
     return result.state;
 }
Beispiel #54
0
    private void RenderDocuments()
    {
        this.LtDocumentsList.Text = string.Empty;
        this.LtDocuments.Text     = string.Empty;

        var files = UploadFile.GetByItem(ItemIdentifiers.BusinessRisk, this.BusinessRiskId, this.Company.Id).ToList();

        if (this.incidentAction.Id > 0)
        {
            files.AddRange(UploadFile.GetByItem(ItemIdentifiers.IncidentActions, this.incidentAction.Id, this.Company.Id));
        }

        var res        = new StringBuilder();
        var resList    = new StringBuilder();
        int contCells  = 0;
        var extensions = ToolsFile.ExtensionToShow;

        foreach (var file in files)
        {
            decimal finalSize  = ToolsFile.FormatSize((decimal)file.Size);
            string  fileShowed = string.IsNullOrEmpty(file.Description) ? file.FileName : file.Description;
            if (fileShowed.Length > 15)
            {
                fileShowed = fileShowed.Substring(0, 15) + "...";
            }

            string viewButton = string.Format(
                CultureInfo.InvariantCulture,
                @"<div class=""col-sm-2 btn-success"" onclick=""ShowPDF('{0}');""><i class=""icon-eye-open bigger-120""></i></div>",
                file.FileName
                );

            string listViewButton = string.Format(
                CultureInfo.InvariantCulture,
                @"<span class=""btn btn-xs btn-success"" onclick=""ShowPDF('{0}');"">
                            <i class=""icon-eye-open bigger-120""></i>
                        </span>",
                file.FileName);

            var fileExtension = Path.GetExtension(file.FileName);

            if (!extensions.Contains(fileExtension))
            {
                viewButton     = "<div class=\"col-sm-2\">&nbsp;</div>";
                listViewButton = "<span style=\"margin-left:30px;\">&nbsp;</span>";
            }

            res.AppendFormat(
                CultureInfo.InvariantCulture,
                @"<div id=""{0}"" class=""col-sm-3 document-container"">
                        <div class=""col-sm-6"">&nbsp</div>
                        {10}
                        <div class=""col-sm-2 btn-info""><a class=""icon-download bigger-120"" href=""/DOCS/{3}/{4}"" target=""_blank"" style=""color:#fff;""></a></div>
                        <div class=""col-sm-2 btn-danger"" onclick=""DeleteUploadFile({0},'{1}');""><i class=""icon-trash bigger-120""></i></div>
                        <div class=""col-sm-12 iconfile"" style=""max-width: 100%;"">
                            <div class=""col-sm-4""><img src=""/images/FileIcons/{2}.png"" /></div>
                            <div class=""col-sm-8 document-name"">
                                <strong title=""{1}"">{9}</strong><br />
                                {7}: {5:dd/MM/yyyy}
                                {8}: {6:#,##0.00} MB
                            </div>
                        </div>
                    </div>",
                file.Id,
                string.IsNullOrEmpty(file.Description) ? file.FileName : file.Description,
                file.Extension,
                this.Company.Id,
                file.FileName,
                file.CreatedOn,
                finalSize,
                this.Dictionary["Item_Attachment_Header_CreateDate"],
                this.Dictionary["Item_Attachment_Header_Size"],
                fileShowed,
                viewButton);

            resList.AppendFormat(
                CultureInfo.InvariantCulture,
                @"<tr id=""tr{2}"">
                    <td>{1}</td>
                    <td align=""center"" style=""width:90px;"">{4:dd/MM/yyyy}</td>
                    <td align=""right"" style=""width:120px;"">{5:#,##0.00} MB</td>
                    <td style=""width:150px;"">
                        {6}
                        <span class=""btn btn-xs btn-info"">
                            <a class=""icon-download bigger-120"" href=""/DOCS/{3}/{0}"" target=""_blank"" style=""color:#fff;""></a>
                        </span>
                        <span class=""btn btn-xs btn-danger"" onclick=""DeleteUploadFile({2},'{1}');"">
                            <i class=""icon-trash bigger-120""></i>
                        </span>
                    </td>
                </tr>",
                file.FileName,
                string.IsNullOrEmpty(file.Description) ? file.FileName : file.Description,
                file.Id,
                this.Company.Id,
                file.CreatedOn,
                finalSize,
                listViewButton);

            contCells++;
            if (contCells == 4)
            {
                contCells = 0;
                res.Append("<div style=\"clear:both\">&nbsp;</div>");
            }
        }

        this.LtDocuments.Text     = res.ToString();
        this.LtDocumentsList.Text = resList.ToString();
    }
Beispiel #55
0
 /// <summary>
 /// 上传DOI注册文件
 /// </summary>
 /// <param name="RegFilePath"></param>
 /// <param name="userName"></param>
 /// <param name="userPwd"></param>
 /// <param name="oprType"></param>
 /// <returns></returns>
 public static string Upload(string RegFilePath, string userName, string userPwd, int oprType)
 {
     StringBuilder sb = new StringBuilder();
     UploadFile uploadFile = new UploadFile();
     UploadResult result = uploadFile.upload(RegFilePath, userName, userPwd, oprType);
     foreach (String file in result.getNewFileNames())
     {
         sb.AppendLine(file);
     }
     return sb.ToString();
 }
Beispiel #56
0
        public void SetUploadedFiles(UploadFile file)
        {
            Files.Add(file);

            CarregaFiles(Files);
        }
        public void SaveEditorFile() {

            Dictionary<String, String> dic = new Dictionary<String, String>();
            Result result = null;
            HttpFile file = null;

            if (ctx.HasUploadFiles == false) {
                errors.Add( "不能上传空图片" );
            } else {
                file = ctx.GetFileSingle();
                result = Uploader.SaveFile( file );
                if (result.HasErrors) {
                    errors.Add( result.ErrorsText );
                }
            }

            if (ctx.HasErrors) {
                dic.Add( "state", errors.ErrorsText );
                echoJson( dic );
                return;
            }

            string savedPath = result.Info.ToString();
            UploadFile f = new UploadFile();
            f.Name = file.FileName;
            f.Path = savedPath;
            f.FileType = (int)FileType.File;
            f.insert();

            dic.Add( "state", "SUCCESS" );
            dic.Add( "url", f.PicO );
            dic.Add( "fileType", f.Ext );
            dic.Add( "original", f.Name );

            echoJson( dic );
        }
        public async Task <IActionResult> Edit(ItemVM itemVM)
        {
            var item = await db.Items.FindAsync(itemVM.Id);

            if (itemVM.Photo != null)
            {
                string fileName = await UploadFile.UploadAsync(webHostEnvironment, itemVM.Photo, photoPath);

                item.Photo = fileName;
            }

            if (itemVM.Document != null)
            {
                string documentName = await UploadFile.UploadAsync(webHostEnvironment, itemVM.Document, documentPath);

                item.Document = documentName;
            }

            item.Title        = itemVM.Title;
            item.Description  = itemVM.Description;
            item.MinimumBid   = itemVM.MinimumBid;
            item.CreatedAt    = itemVM.CreatedAt;
            item.BidStatus    = itemVM.BidStatus;
            item.BidEndDate   = itemVM.BidEndDate;
            item.BidStartDate = itemVM.BidStartDate;
            if (itemVM.SelectedCategoryIds != null)
            {
                var categoryitems = db.CategoryItems.Where(c => c.ItemId == itemVM.Id).ToList();
                if (categoryitems.Count > 0)
                {
                    foreach (var categoryitem in categoryitems)
                    {
                        item.CategoryItems.Remove(categoryitem);
                    }
                }
                foreach (var cateId in itemVM.SelectedCategoryIds)
                {
                    item.CategoryItems.Add(new CategoryItem
                    {
                        CategoryId = cateId,
                        ItemId     = item.Id,
                        CreatedAt  = DateTime.Now
                    });
                }
                db.Items.Add(item);

                try
                {
                    db.Update(item);
                    await db.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!ItemExists(item.Id))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        ModelState.AddModelError("", "Unable to save changes. " +
                                                 "Try again, and if the problem persists, " +
                                                 "see your system administrator.");
                    }
                }

                return(RedirectToAction("Detail", "Item", new { id = itemVM.Id }));
            }

            layoutVM.ItemVM            = itemVM;
            layoutVM.ItemVM.Categories = db.Categories.Select(a =>
                                                              new SelectListItem
            {
                Value = a.Id.ToString(),
                Text  = a.Name
            }).ToList();

            return(View(layoutVM));
        }
Beispiel #59
0
    /// <summary>
    /// Attempts to upload a single file a Tableau Server, and then make it a published workbook
    /// </summary>
    /// <param name="localFilePath"></param>
    /// <returns></returns>
    private bool AttemptUploadSingleFile_Inner(
        string localFilePath, 
        string projectId, 
        CredentialManager.Credential dbCredentials,
        WorkbookPublishSettings publishSettings)
    {
        string uploadSessionId;
        try
        {
            var fileUploader = new UploadFile(_onlineUrls, _onlineSession, localFilePath, _uploadChunkSizeBytes, _uploadChunkDelaySeconds);
            uploadSessionId = fileUploader.ExecuteRequest();
        }
        catch (Exception exFileUpload)
        {
            this.StatusLog.AddError("Unexpected error attempting to upload file " + localFilePath + ", " + exFileUpload.Message);
            throw exFileUpload;
        }

        SiteWorkbook workbook;
        this.StatusLog.AddStatus("File chunks upload successful. Next step, make it a published workbook", -10);
        try
        {
            string fileName = Path.GetFileNameWithoutExtension(localFilePath);
            string uploadType = RemoveFileExtensionDot(Path.GetExtension(localFilePath).ToLower());
            workbook = FinalizePublish(
                uploadSessionId,
                FileIOHelper.Undo_GenerateWindowsSafeFilename(fileName), //[2016-05-06] If the name has escapted characters, unescape them
                uploadType,
                projectId,
                dbCredentials,
                publishSettings);
            StatusLog.AddStatus("Upload content details: " + workbook.ToString(), -10);
            StatusLog.AddStatus("Success! Uploaded workbook " + Path.GetFileName(localFilePath));
        }
        catch (Exception exPublishFinalize)
        {
            this.StatusLog.AddError("Unexpected error finalizing publish of file " + localFilePath + ", " + exPublishFinalize.Message);
            LogManualAction_UploadWorkbook(localFilePath);
            throw exPublishFinalize;
        }

        //See if we want to reassign ownership of the workbook
        if(_attemptOwnershipAssignment)
        {
            try
            {
                AttemptOwnerReassignment(workbook, publishSettings, _siteUsers);
            }
            catch (Exception exOwnershipAssignment)
            {
                this.StatusLog.AddError("Unexpected error reassigning ownership of published workbook " + workbook.Name + ", " + exOwnershipAssignment.Message);
                LogManualAction_ReassignOwnership(workbook.Name);
                throw exOwnershipAssignment;
            }
        }

        return true;     //Success
    }
    protected void SubmitButton_Click(object sender, EventArgs e)
    {
        try
        {
            //Confirm that we have a muid to access upload data
            System.Diagnostics.Debug.Assert(!String.IsNullOrEmpty(Request.QueryString[UploadMonitor.UploadIdParam]));
            UploadData objUploadData = UploadMonitor.GetUploadData(Request.QueryString[UploadMonitor.UploadIdParam]);
            if (objUploadData == null)
            {
                throw new ApplicationException("Oops! No upload data");
            }

            //Check any exception
            Exception objUploadException = objUploadData.Exception;
            if (objUploadException != null)
            {
                throw new ApplicationException(objUploadException.Message, objUploadException);
            }

            //Ensure that upload is complete
            if (objUploadData.ProgressStatus != UploadProgressStatus.Completed)
            {
                throw new ApplicationException("Oops! Upload not complete");
            }

            //Ensure we have at least one uploaded file (we should have at least one file input control)
            if ((objUploadData.UploadFiles == null) || (objUploadData.UploadFiles.Count < 1))
            {
                throw new ApplicationException("Oops! No uploaded file");
            }

            //Keep it simple: we now there is only one file upload control on the page
            UploadFile objUploadFile = objUploadData.UploadFiles[0];
            if ((objUploadFile == null) || (!objUploadFile.IsComplete))
            {
                throw new ApplicationException("Oops! Uploaded file is not complete");
            }

            //Create file object
            File f = new File(
                objUploadFile.OriginalFileName,
                objUploadFile.ContentType,
                objUploadFile.ProviderFileKey.ToString(),
                objUploadFile.ContentLength,
                objUploadFile.HashValue);

            //Get path to file storage
            string sPath = FileStorage.Provider.ConnectionString;
            System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(sPath);

            //Add definition to file storage
            FileBroker.Insert(f, di);

            //Create download link
            DownloadLink.Text        = "Download: " + f.FileName + " (" + BODisplay.SizeFormat(f.Size, ByteFormat.Adapt) + ")";
            DownloadLink.NavigateUrl = System.IO.Path.Combine(this.Request.ApplicationPath, f.Guid.ToString("N") + ".dat");

            //Release upload data
            UploadMonitor.Release(objUploadData.UploadId);
        }
        catch (Exception Ex)
        {
            Response.Write(Ex.Message);
        }
    }