示例#1
0
        private void OnUpload(object sender, System.EventArgs e)
        {
            try
            {
                if (m_objUser == null)
                {
                    throw new Exception("Your session has expired.");
                }

                System.Web.HttpFileCollection uploadedFiles = Request.Files;
                BSLCompany objCompany     = m_objUser.GetCompany();
                string     strDataDirName = objCompany.TCompanies[0].rootDirName;
                string     strInputDir    = (string)Cache["G2_DATA_PATH"];
                strInputDir += (!strInputDir.EndsWith("\\") ? "\\" : "") +
                               strDataDirName;
                strInputDir += (!strInputDir.EndsWith("\\") ? "\\" : "") +
                               "Input";

                for (int i = 0; i < uploadedFiles.Count; i++)
                {
                    System.Web.HttpPostedFile postedFile = uploadedFiles[i];
                    string strFileName = System.IO.Path.GetFileName(postedFile.FileName);
                    postedFile.SaveAs(strInputDir + "\\" + strFileName);
                }
                string strScript = "<script for='window' event='onload' language='javascript'>alert('File(s) uploaded successfully.');</script>";
                RegisterStartupScript("SuccessMsg", strScript);
            }
            catch (Exception ex)
            {
                lblMsg.Visible = true;
                lblMsg.Text    = ex.Message;
            }
        }
        /// <summary>
        /// Saving new file attachments.
        /// </summary>
        /// <param name="fileCollection">Collection of posted files.</param>
        /// <param name="person"></param>
        public void SavePhotoAttachmentFiles(HttpFileCollection fileCollection, Person person)
        {
            for (int i = 0; i < fileCollection.Count; i++)
            {
                HttpPostedFile file = fileCollection[i];

                if (file.FileName != null && !String.IsNullOrEmpty(file.FileName))
                {
                    String uniqueName = String.Empty;
                    String fileName = String.Empty;

                    fileName = file.FileName.Replace("/", "\\");
                    int index = fileName.LastIndexOf("\\");
                    fileName = fileName.Substring(index + 1);

                    // уникальное имя файла на сервере
                    uniqueName = Guid.NewGuid() + "_" + fileName;

                    //добавляем информацию о фото в БД
                    person.AddStandardStringAttribute(PersonAttributeTypes.Photo, uniqueName);

                    SaveFile(file, uniqueName);
                }
            }
        }
示例#3
0
        public ActionResult Upload(tbl_gallery glry)
        {
            tbl_dispImg dsply = new tbl_dispImg();

            System.Web.HttpFileCollection files = System.Web.HttpContext.Current.Request.Files;
            for (int i = 0; i < files.Count; i++)
            {
                System.Web.HttpPostedFile file = files[i];
                string extension = Path.GetExtension(file.FileName);
                string location  = "/Uploads/" + file.FileName.Replace(" ", "");
                file.SaveAs(Server.MapPath(location));
                glry.FileName = location;

                db.tbl_gallery.Add(glry);
                db.SaveChanges();
            }
            System.Web.HttpPostedFile filex = files[0];
            string extensionx = Path.GetExtension(filex.FileName);
            string locationx  = "/Uploads/" + filex.FileName.Replace(" ", "");

            filex.SaveAs(Server.MapPath(locationx));
            dsply.FilePath  = locationx;
            dsply.CompanyID = glry.CompanyID;
            db.tbl_dispImg.Add(dsply);

            db.SaveChanges();

            return(Json("1", JsonRequestBehavior.AllowGet));
        }
示例#4
0
        public void UpFile()
        {
            System.Web.HttpFileCollection _file = System.Web.HttpContext.Current.Request.Files;
            if (_file.Count > 0)
            {
                //文件大小
                long size = _file[0].ContentLength;
                //文件类型
                string type = _file[0].ContentType;
                //文件名
                string name = _file[0].FileName;
                //文件格式
                string _tp = System.IO.Path.GetExtension(name);

                //if (_tp.ToLower() == ".jpg" || _tp.ToLower() == ".jpeg" || _tp.ToLower() == ".gif" || _tp.ToLower() == ".png" || _tp.ToLower() == ".swf")
                //{
                //获取文件流
                System.IO.Stream stream = _file[0].InputStream;
                //保存文件
                string saveName = DateTime.Now.ToString("yyyyMMddHHmmss") + _tp;
                string path     = HttpContext.Current.Server.MapPath("/Test/temp/");
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
                _file[0].SaveAs(path + saveName);
                //}
            }
        }
示例#5
0
 protected void Page_Load(object sender, EventArgs e)
 {
     if (!IsPostBack)
     {
        System.Web.HttpFileCollection uploadFiles = request.Files;//获取需要上传的文件
    System.Web.HttpPostedFile theFile;
    string savepath = Server.MapPath(".") + "\\templateFile\\";
     if (uploadFiles.Count == 0)
     {
         response.Write("没有文件上传!");
     }
     else
     {
         for (int i = 0; i < uploadFiles.Count; i++)
         {
             theFile = uploadFiles[i];
             if (uploadFiles.GetKey(i) == "upLoadFile")
             {
                 string myfileName = Request.Params["filename"];
                 myfileName = Server.UrlDecode(myfileName);
                 theFile.SaveAs(savepath + theFile.FileName);
                 response.Write("保存成功!");
             }
         }
     }
 }
     }
示例#6
0
        //插入
        protected string add_fields()
        {
            System.Web.HttpFileCollection files = System.Web.HttpContext.Current.Request.Files;
            string fpath     = "";
            int    fileCount = 0;

            for (fileCount = 0; fileCount < files.Count; fileCount++)
            {
                //定义访问客户端上传文件的对象
                System.Web.HttpPostedFile postedFile = files[fileCount];
                string fileName, fileExtension;
                //取得上传得文件名
                fileName = System.IO.Path.GetFileName(postedFile.FileName);
                if (fileName != String.Empty)
                {
                    //取得文件的扩展名
                    fileExtension = System.IO.Path.GetExtension(fileName);
                    SafeSC.SaveFile("/UploadFiles/" + buser.GetLogin().UserName + "/我的文档/", postedFile, fileName);
                    if (fileCount == 0)
                    {
                        fpath += buser.GetLogin().UserName + "\\我的文档\\" + fileName;
                    }
                    else
                    {
                        fpath += "|" + buser.GetLogin().UserName + "\\我的文档\\" + fileName;
                    }
                }
            }
            return(fpath);
        }
示例#7
0
        public HttpResponseMessage UploadFiles()
        {
            var httpRequest = HttpContext.Current.Request;

            //Upload Image
            System.Web.HttpFileCollection hfc = System.Web.HttpContext.Current.Request.Files;
            string ff = "";

            try
            {
                for (int iCnt = 0; iCnt <= hfc.Count - 1; iCnt++)
                {
                    System.Web.HttpPostedFile hpf = hfc[iCnt];
                    if (hpf.ContentLength > 0)
                    {
                        var filename = (Path.GetFileName(hpf.FileName));
                        var filePath = HttpContext.Current.Server.MapPath("~/Static/" + filename);
                        hpf.SaveAs(filePath);
                        //VideoMaster obj = new VideoMaster();
                        ff = filePath + filename;
                        //obj.Videos = "http://localhost:50401/Vedios/" + filename;
                        //wmsEN.VideoMasters.Add(obj);
                        //wmsEN.SaveChanges();
                    }
                }
            }
            catch (Exception ex)
            { }
            var rq = Request.CreateResponse <string>(HttpStatusCode.Created, ff);

            return(rq);
        }
示例#8
0
        public async Task <IHttpActionResult> Upload(Guid id)
        {
            string root = System.Web.HttpContext.Current.Server.MapPath("~/App_Data/uploads/" + id);

            if (!Directory.Exists(root))
            {
                Directory.CreateDirectory(root);
            }
            else
            {
                foreach (string enumerateFile in Directory.EnumerateFiles(root))
                {
                    File.Delete(enumerateFile);
                }
            }

            System.Web.HttpFileCollection hfc = System.Web.HttpContext.Current.Request.Files;

            // CHECK THE FILE COUNT.
            for (int iCnt = 0; iCnt <= hfc.Count - 1; iCnt++)
            {
                System.Web.HttpPostedFile hpf = hfc[iCnt];


                var r = Path.Combine(root, "logo.jpg");

                hpf.SaveAs(r);

                return(Ok());
            }



            return(BadRequest());
        }
        public IHttpActionResult Save()
        {
            Dictionary <string, object> RetData = new Dictionary <string, object>();

            try
            {
                var      model  = HttpContext.Current.Request.Form["record"];
                Companym record = JsonConvert.DeserializeObject <Companym>(model);

                using (CompanyService obj = new CompanyService())
                {
                    RetData = obj.Save(record);
                }

                System.Web.HttpFileCollection hfc = System.Web.HttpContext.Current.Request.Files;

                for (int iCnt = 0; iCnt <= hfc.Count - 1; iCnt++)
                {
                    Lib.UploadFile(hfc[iCnt], record._globalvariables.comp_code, record.comp_pkid, hfc.Keys[iCnt]);
                }

                return(Ok(RetData));
            }
            catch (Exception Ex)
            {
                return(ResponseMessage(Request.CreateErrorResponse(HttpStatusCode.BadRequest, Ex.Message.ToString())));
            }
        }
 public HttpFileCollectionWrapper(HttpFileCollection httpFileCollection)
 {
     if (httpFileCollection == null) {
         throw new ArgumentNullException("httpFileCollection");
     }
     _collection = httpFileCollection;
 }
        public IHttpActionResult SaveDet()
        {
            int islno = 0;
            Dictionary <string, object> RetData = new Dictionary <string, object>();

            try
            {
                Dictionary <string, object> SearchData = new Dictionary <string, object>();
                var       model  = HttpContext.Current.Request.Form["record"];
                pim_spotd record = JsonConvert.DeserializeObject <pim_spotd>(model);
                using (SpotService obj = new SpotService())
                {
                    RetData = obj.SaveDet(record);
                    islno   = Lib.Conv2Integer(RetData["slno"].ToString());
                }
                System.Web.HttpFileCollection hfc = System.Web.HttpContext.Current.Request.Files;
                for (int iCnt = 0; iCnt <= hfc.Count - 1; iCnt++)
                {
                    Lib.UploadFile(hfc[iCnt], record._globalvariables.comp_code, record.spotd_pkid, hfc.Keys[iCnt]);
                }
                return(Ok(RetData));
            }
            catch (Exception Ex)
            {
                return(ResponseMessage(Request.CreateErrorResponse(HttpStatusCode.BadRequest, Ex.Message.ToString())));
            }
        }
示例#12
0
文件: Image.cs 项目: kallex/Caloom
 public bool PerformAddOperation(string commandName, InformationSourceCollection sources, string requesterLocation, HttpFileCollection files)
 {
     string[] cmdIDList = commandName.Split('_');
     if (cmdIDList.Length < 2)
         return false;
     string cmd = cmdIDList[0];
     string cmdID = cmdIDList[1];
     if (cmdID != this.ID)
         return false;
     var defaultSource = sources.GetDefaultSource(typeof(ImageGroup).FullName);
     ImageGroup currImageGroup = (ImageGroup) defaultSource.RetrieveInformationObject();
     VirtualOwner owner = VirtualOwner.FigureOwner(this);
     Image addedImage = Image.CreateDefault();
     addedImage.CopyContentFrom(this);
     addedImage.ImageData = MediaContent.CreateDefault();
     HttpPostedFile postedFile = files[this.ImageData.ID];
     if (postedFile != null && String.IsNullOrWhiteSpace(postedFile.FileName) == false)
     {
         addedImage.SetMediaContent(owner, addedImage.ImageData.ID,
             new MediaFileData { HttpFile = postedFile});
     }
     currImageGroup.ImagesCollection.CollectionContent.Add(addedImage);
     currImageGroup.StoreInformationMasterFirst(owner, true);
     return true;
 }
示例#13
0
 protected void Page_Load(object sender, System.EventArgs e)
 {
     System.Web.HttpFileCollection files = base.Request.Files;
     if (files.Count > 0)
     {
         string str = System.Web.HttpContext.Current.Request.MapPath(Globals.ApplicationPath + "/Storage/master/flex");
         System.Web.HttpPostedFile file = files[0];
         string str2 = System.IO.Path.GetExtension(file.FileName).ToLower();
         if (str2 != ".jpg" && str2 != ".gif" && str2 != ".jpeg" && str2 != ".png" && str2 != ".bmp")
         {
             base.Response.Write("1");
         }
         else
         {
             string s        = System.DateTime.Now.ToString("yyyyMMdd") + new System.Random().Next(10000, 99999).ToString(System.Globalization.CultureInfo.InvariantCulture) + str2;
             string filename = str + "/" + s;
             try
             {
                 file.SaveAs(filename);
                 base.Response.Write(s);
             }
             catch
             {
                 base.Response.Write("0");
             }
         }
     }
     else
     {
         base.Response.Write("2");
     }
 }
示例#14
0
    /// <summary>
    /// 提交
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void LinkButton_Next_Click(object sender, EventArgs e)
    {
        System.Web.HttpFileCollection files  = System.Web.HttpContext.Current.Request.Files;
        System.Text.StringBuilder     strmsg = new System.Text.StringBuilder("");

        string strMSG = string.Empty;
        int    ifile;

        for (ifile = 0; ifile < files.Count; ifile++)
        {
            //MessageBox("", files.Count.ToString());
            if (files[ifile].FileName.Length > 0)
            {
                //System.Web.HttpPostedFile postedfile = files[ifile];
                //if (postedfile.ContentLength / 1024 > 1024)//单个文件不能大于1024k
                //{
                //    strmsg.Append(Path.GetFileName(postedfile.FileName) + "---不能大于1024k<br>");
                //    break;
                //}
                //string fex = Path.GetExtension(postedfile.FileName);
                //if (fex != ".jpg" && fex != ".JPG" && fex != ".gif" && fex != ".GIF")
                //{
                //    strmsg.Append(Path.GetFileName(postedfile.FileName) + "---图片格式不对,只能是jpg或gif<br>");
                //    break;
                //}
                strMSG += files[ifile].FileName.ToString() + ",";
                strMSG += strmsg[ifile].ToString() + ",";
            }
        }
        MessageBox("", "[" + strMSG + "]");
    }
示例#15
0
        /// <summary>
        /// 文件上传
        /// </summary>
        /// <param name="hfc">客户端上传文件流</param>
        /// <param name="afterPath">类似:aaaa/bbb/子文件夹</param>
        /// <returns></returns>
        public static List<string> MvcUpload(HttpFileCollection hfc, string afterPath = "")
        {
            string path = string.Format("{0}{1}{2}/", UploadRoot, afterPath, DateTime.Today.ToString("yyyyMMdd"));

            List<string> theList = new List<string>();

            string filePath = HostingEnvironment.MapPath(path);
            if (!Directory.Exists(filePath))
            {
                Directory.CreateDirectory(filePath);
            }

            foreach (string itemKey in hfc)
            {
                HttpPostedFile item = hfc[itemKey];
                if (item != null && item.ContentLength == 0) continue;

                string fileExtension = Path.GetExtension(item.FileName);
                var fileName = Guid.NewGuid() + fileExtension;
                item.SaveAs(filePath + fileName);

                string strSqlPath = (path + fileName).Replace("~/", ServerHost);
                theList.Add(strSqlPath);
            }
            return theList;
        }
        public IHttpActionResult UploadResource()
        {
            //throw new Exception("forced error");
            HttpResponseMessage response = new HttpResponseMessage();
            var             httpRequest  = HttpContext.Current.Request;
            DigitalResource myResource   = null;

            //DigitalResource resource = null;
            //if (albumID != null)
            {
                System.Web.HttpFileCollection files         = System.Web.HttpContext.Current.Request.Files;
                Repository.ResourceRepository repository    = new Repository.ResourceRepository();
                ReferenceRepository           refRepository = new ReferenceRepository();
                UserRepository ur          = new UserRepository();
                string         currentUser = User.Identity.Name;
                User           user        = ur.Get(currentUser);
                //Album album = repository.GetAlbums(x => x.Name == albumID).FirstOrDefault();

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

                    string name = file.FileName;
                    using (Stream fileStream = file.InputStream)
                    {
                        myResource = repository.SaveOrGet(refRepository, user, fileStream, name);
                    }
                }
            }

            return(Ok(myResource));
        }
示例#17
0
        public static string UploadFile(string fileDir, string appSettingName)
        {
            string saveFilePath = AppDomain.CurrentDomain.BaseDirectory + "\\" + System.Configuration.ConfigurationSettings.AppSettings[appSettingName];

            System.Web.HttpFileCollection files = System.Web.HttpContext.Current.Request.Files;
            string fileName = "";

            if (fileDir.Trim().Equals(string.Empty))
            {
                return("");
            }

            if (!System.IO.Directory.Exists(saveFilePath))
            {
                System.IO.Directory.CreateDirectory(saveFilePath);
            }

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

                if (!file.FileName.Equals(fileDir))
                {
                    continue;
                }

                fileName = System.IO.Path.GetFileName(file.FileName);

                fileName = FileOverLapCheck(saveFilePath, fileName);
                file.SaveAs(saveFilePath + "\\" + fileName);                                    // 업로드 한다.
            }

            return(fileName);
        }
示例#18
0
        public string TestFiles()
        {
            int iUploadedCnt = 0;

            // DEFINE THE PATH WHERE WE WANT TO SAVE THE FILES.
            string sPath = "";

            sPath = System.Web.Hosting.HostingEnvironment.MapPath("~/Content/");

            System.Web.HttpFileCollection hfc = System.Web.HttpContext.Current.Request.Files;

            // CHECK THE FILE COUNT.
            for (int iCnt = 0; iCnt <= hfc.Count - 1; iCnt++)
            {
                System.Web.HttpPostedFile hpf = hfc[iCnt];

                if (hpf.ContentLength > 0)
                {
                    hpf.SaveAs(sPath + Path.GetFileName(hpf.FileName));
                    iUploadedCnt = iUploadedCnt + 1;
                }
            }

            // RETURN A MESSAGE (OPTIONAL).
            if (iUploadedCnt > 0)
            {
                return(iUploadedCnt + " Files Uploaded Successfully");
            }
            else
            {
                return("File not received\n");
            }
        }
示例#19
0
        public String POST()
        {
            int counts = 0;

            System.Web.HttpFileCollection files = System.Web.HttpContext.Current.Request.Files;
            string url       = HttpContext.Current.Request.Url.AbsoluteUri;
            Pics   prodimage = new Pics();

            String Status = "";

            for (int m = 0; m < files.Count; m++)
            {
                //get files(product pictures)
                System.Web.HttpPostedFile file = files[m];
                string filename = new FileInfo(file.FileName).Name;

                if (file.ContentLength > 0)
                {
                    Guid   id = Guid.NewGuid();
                    string modifiedFileName = id.ToString() + "_" + filename;
                    byte[] imageprod        = new byte[file.ContentLength];
                    file.InputStream.Read(imageprod, 0, file.ContentLength);

                    prodimage.Image = imageprod;
                    db.Pics1.Add(prodimage);
                    db.SaveChanges();
                    counts++;
                }
            }
            if (counts > 0)
            {
                return(Status);
            }
            return("Upload was unsuccesful");
        }
示例#20
0
        public string UploadSiteProgress()
        {
            int iUploadedCnt = 0;

            // DEFINE THE PATH WHERE WE WANT TO SAVE THE FILES.
            string sPath = "";

            sPath = System.Web.Hosting.HostingEnvironment.MapPath("~/SiteProgress/");

            System.Web.HttpFileCollection hfc = System.Web.HttpContext.Current.Request.Files;

            string FileNa      = "";
            var    renamedFile = RandomString(10);

            renamedFile = "SiteProgress_" + renamedFile + "_" + System.DateTime.Now.ToString("dd-MM-yyyy");
            // CHECK THE FILE COUNT.
            for (int iCnt = 0; iCnt <= hfc.Count - 1; iCnt++)
            {
                System.Web.HttpPostedFile hpf = hfc[iCnt];

                if (hpf.ContentLength > 0)
                {
                    var filename = Path.GetExtension(hpf.FileName);
                    // CHECK IF THE SELECTED FILE(S) ALREADY EXISTS IN FOLDER. (AVOID DUPLICATE)
                    if (!File.Exists(sPath + Path.GetFileName(renamedFile + filename)))
                    {
                        // SAVE THE FILES IN THE FOLDER.
                        hpf.SaveAs(sPath + Path.GetFileName(renamedFile + filename));
                        FileNa       = renamedFile + filename;
                        iUploadedCnt = iUploadedCnt + 1;
                    }
                }
            }
            return(FileNa);
        }
示例#21
0
        public IHttpActionResult Post()
        {
            System.Web.HttpFileCollection hfc = System.Web.HttpContext.Current.Request.Files;

            if (hfc.Count != 1)
            {
                throw new Exception("method only supports one file at a time");
            }
            HttpPostedFile vFile = hfc[0];

            _documents.InsertDataFileVip(vFile.FileName, vFile.InputStream, vFile.ContentType);

            return(Ok("test"));


            //if (string.IsNullOrWhiteSpace(fileContent))
            //    throw new ArgumentNullException("file");

            //_documents.InsertDataFileVip(fileContent);

            //// var data = _fileResponse.SaveSchema(versionType, json);
            //return Ok();

            ////if (!Request.Content.IsMimeMultipartContent())
            ////    throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);

            ////var provider = new MultipartMemoryStreamProvider();
            ////await Request.Content.ReadAsMultipartAsync(provider);
            ////foreach (var file in provider.Contents)
            ////{
            ////    var filename = file.Headers.ContentDisposition.FileName.Trim('\"');
            ////    var buffer = await file.ReadAsByteArrayAsync();
            ////    //Do whatever you want with filename and its binaray data.
            ////}
        }
示例#22
0
        public string UploadUpdatedFiles()
        {
            string sPath = "";

            sPath = System.Web.Hosting.HostingEnvironment.MapPath("~/Images/");
            var request = System.Web.HttpContext.Current.Request;

            System.Web.HttpFileCollection hfc = System.Web.HttpContext.Current.Request.Files;
            //var remark = request["remark"].ToString();
            if (hfc != null)
            {
                for (int iCnt = 0; iCnt <= hfc.Count - 1; iCnt++)
                {
                    System.Web.HttpPostedFile hpf = hfc[iCnt];
                    if (hpf.ContentLength > 0)
                    {
                        string FileName = (Path.GetFileName(hpf.FileName));
                        //if (!File.Exists(sPath + FileName))
                        //{
                        // SAVE THE FILES IN THE FOLDER.
                        hpf.SaveAs(sPath + FileName);
                        PROPERTYPHOTO obj = new PROPERTYPHOTO();
                        obj.PHOTO      = FileName;
                        obj.PROPERTYID = Convert.ToInt32(request["PropertyID"]);
                        img.PROPERTYPHOTOes.Add(obj);
                        img.SaveChanges();
                        //}
                    }
                }
            }
            return("Upload Failed");
        }
示例#23
0
        public HttpResponseMessage UploadFile(string tmppath)
        {
            int    iUploadedCnt = 0;
            Result resData      = new Result();

            try
            {
                // DEFINE THE PATH WHERE WE WANT TO SAVE THE FILES.
                string sPath = "";
                sPath = System.Web.Hosting.HostingEnvironment.MapPath("~/tmpUpload/" + tmppath + "/");
                if (!Directory.Exists(sPath))
                {
                    Directory.CreateDirectory(sPath);
                }
                else
                {
                    System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(sPath);
                    foreach (System.IO.FileInfo file in di.GetFiles())
                    {
                        file.Delete();
                    }
                }
                System.Web.HttpFileCollection hfc = System.Web.HttpContext.Current.Request.Files;

                // CHECK THE FILE COUNT.
                for (int iCnt = 0; iCnt <= hfc.Count - 1; iCnt++)
                {
                    System.Web.HttpPostedFile hpf = hfc[iCnt];

                    if (hpf.ContentLength > 0)
                    {
                        // CHECK IF THE SELECTED FILE(S) ALREADY EXISTS IN FOLDER. (AVOID DUPLICATE)
                        if (!File.Exists(sPath + Path.GetFileName(hpf.FileName)))
                        {
                            // SAVE THE FILES IN THE FOLDER.
                            hpf.SaveAs(sPath + Path.GetFileName(hpf.FileName));
                            iUploadedCnt = iUploadedCnt + 1;
                        }
                    }
                }
                resData.StatusCode = (int)(StatusCodes.Succuss);

                // RETURN A MESSAGE (OPTIONAL).
                if (iUploadedCnt > 0)
                {
                    resData.Messages = iUploadedCnt + " Files Uploaded Successfully";
                }
                else
                {
                    resData.Messages = "Upload Failed";
                }
            }
            catch (Exception ex)
            {
                resData.StatusCode = (int)(StatusCodes.Error);
                resData.Messages   = ex.Message;;
            }
            return(Request.CreateResponse(HttpStatusCode.OK, resData));
        }
示例#24
0
 protected void Page_Load(object sender, EventArgs e)
 {
     System.Web.HttpFileCollection _file = System.Web.HttpContext.Current.Request.Files;
     if (_file.Count > 0)
     {
         IsCheck(_file);
     }
 }
示例#25
0
        public static object ExecuteOwnerWebPOST(IContainerOwner containerOwner, NameValueCollection form, HttpFileCollection fileContent)
        {
            bool reloadPageAfter = form["NORELOAD"] == null;

            bool isCancelButton = form["btnCancel"] != null;
            if (isCancelButton)
                return reloadPageAfter;

            string operationName = form["ExecuteOperation"];
            if (operationName != null)
            {
                var operationResult = executeOperationWithFormValues(containerOwner, operationName, form, fileContent);
                if(operationResult != null)
                    return operationResult;
                return reloadPageAfter;
            }

            string adminOperationName = form["ExecuteAdminOperation"];
            if (adminOperationName != null)
            {
                var adminResult = executeAdminOperationWithFormValues(containerOwner, adminOperationName, form, fileContent);
                if(adminResult != null)
                    return adminResult;
                return reloadPageAfter;
            }

            string contentSourceInfo = form["ContentSourceInfo"];
            var rootSourceAction = form["RootSourceAction"];
            if (rootSourceAction != null && rootSourceAction != "Save")
                return reloadPageAfter;
            var filterFields = new string[] { "ContentSourceInfo", "RootSourceAction", "NORELOAD" };
            string[] contentSourceInfos = contentSourceInfo.Split(',');
            var filteredForm = filterForm(form, filterFields);
            foreach (string sourceInfo in contentSourceInfos)
            {
                string relativeLocation;
                string oldETag;
                retrieveDataSourceInfo(sourceInfo, out relativeLocation, out oldETag);
                VirtualOwner verifyOwner = VirtualOwner.FigureOwner(relativeLocation);
                if (verifyOwner.IsSameOwner(containerOwner) == false)
                    throw new SecurityException("Mismatch in ownership of data submission");
                IInformationObject rootObject = StorageSupport.RetrieveInformation(relativeLocation, oldETag,
                                                                                   containerOwner);
                if (oldETag != rootObject.ETag)
                {
                    throw new InvalidDataException("Information under editing was modified during display and save");
                }
                // TODO: Proprely validate against only the object under the editing was changed (or its tree below)

                SetObjectTreeValues.Execute(new SetObjectTreeValuesParameters
                    {
                        RootObject = rootObject,
                        HttpFormData = filteredForm,
                        HttpFileData = fileContent
                    });
            }
            return reloadPageAfter;
        }
        public ResponseViewModel UploadProfilePic()
        {
            try
            {
                var       info   = new ResponseViewModel();
                ContactVM import = new ContactVM();
                string    sPath  = "~/PropertyPhotos/ProfilePhotos/";
                sPath = System.Web.Hosting.HostingEnvironment.MapPath(sPath);
                Guid guid = Guid.NewGuid();
                System.Web.HttpFileCollection hfc = System.Web.HttpContext.Current.Request.Files;
                var FolderName = System.Web.HttpContext.Current.Request.Form;
                import.Id = Convert.ToInt64(FolderName["ContactID"]);

                for (int iCnt = 0; iCnt <= hfc.Count - 1; iCnt++)
                {
                    //import.PhotoTypeID = iCnt + 4;
                    System.Web.HttpPostedFile hpf = hfc[iCnt];

                    if (hpf.ContentLength > 0)
                    {
                        var savedFilePath = (System.Web.HttpContext.Current.Request.PhysicalApplicationPath + @"PropertyPhotos\ProfilePhotos\");
                        if (!Directory.Exists(savedFilePath))
                        {
                            Directory.CreateDirectory(savedFilePath);
                        }
                        import.PhotoPath = sPath + "\\" + guid + ".jpg";
                        if (!File.Exists(import.PhotoPath))
                        {
                            hpf.SaveAs(import.PhotoPath);
                            import.PhotoPath = hpf.FileName;
                            import.PhotoPath = "../PropertyPhotos/ProfilePhotos/" + "/" + guid + ".jpg";
                            // var conct = _contactrepository.GetSingle(import.ID);
                            //var newcnct = _contactrepository.GetSingle(import.ID);
                            //newcnct.PhotoPath = "../PropertyPhotos/ProfilePhotos/" + "/" + guid + ".jpg";
                            //_contactrepository.Edit(conct, newcnct);
                            _unitOfWork.Commit();
                        }
                    }
                }
                var model = ""; //_contactrepository.GetSingle(import.ID);
                responseViewModel.Content   = model;
                responseViewModel.IsSuccess = true;
            }
            catch (Exception ex)
            {
                responseViewModel.IsSuccess = false;
                if (responseViewModel.ReturnMessage != null && responseViewModel.ReturnMessage.Count > 0)
                {
                    responseViewModel.ReturnMessage.Add(ex.Message);
                }
                else
                {
                    responseViewModel.ReturnMessage = new List <string>();
                    responseViewModel.ReturnMessage.Add(ex.Message);
                }
            }
            return(responseViewModel);
        }
示例#27
0
    protected void Button1_Click(object sender, EventArgs e)
    {
        try
        {
            System.Web.HttpFileCollection uploadFiles = Request.Files;
            System.Web.HttpPostedFile     theFile;
            for (int i = 0; i < uploadFiles.Count; i++)
            {
                theFile = uploadFiles[i];
                if (Convert.ToDouble(theFile.ContentLength) / 1024 / 1024 > 10)
                {
                    Tunnel.Common.Message.back("附件大小不能大于10MB");
                    return;
                }
                else
                {
                    continue;
                }
            }
            string curruser = m_value.Value;
            //将当前步骤存入数据库表:Tunnel_exam
            Tunnel.BLL.Tunnel_exam     bte = new Tunnel.BLL.Tunnel_exam();
            Tunnel.Model.Tunnel_exam   mte = new Tunnel.Model.Tunnel_exam();
            Tunnel.Model.Tunnel_Remind tr  = new Tunnel.Model.Tunnel_Remind();
            Tunnel.BLL.Tunnel_Remind   br  = new Tunnel.BLL.Tunnel_Remind();
            mte.e_bid       = 0;
            mte.e_endtime   = DateTime.Now;
            mte.e_gid       = this.sava();
            mte.e_user      = 0;
            mte.e_time      = DateTime.Now;
            mte.e_nextbuser = curruser;
            mte.e_nextbid   = 1;
            bte.Add(mte);
            string[] users = curruser.Split(',');
            foreach (string user in users)
            {
                if (!string.IsNullOrEmpty(user))
                {
                    tr.m_title    = TextBox1.Text.Trim() + "<font color=red>(待审批)</font>";
                    tr.m_url      = "N_WorkFlow/OtherDocument/Other_zSp.aspx?bid=" + mte.e_gid;
                    tr.m_touser   = Convert.ToInt32(user);
                    tr.m_time     = DateTime.Now;
                    tr.m_type     = 1;
                    tr.m_typeid   = mte.e_gid;
                    tr.m_bid      = 1;
                    tr.m_callTime = Convert.ToDateTime("1800-1-1 00:00:00");
                    tr.m_isread   = 0;
                    long messge = br.Add(tr);
                }
            }

            Tunnel.Common.Message.Show("提交成功!");
        }
        catch
        {
            Tunnel.Common.Message.back("流程错误,请与管理员联系!");
        }
    }
 public static SetObjectTreeValuesParameters SetObjectValues_GetParameters(NameValueCollection httpFormData, HttpFileCollection httpFileData, IInformationObject createdObject)
 {
     return new SetObjectTreeValuesParameters
         {
             RootObject = createdObject,
             HttpFormData = httpFormData,
             HttpFileData = httpFileData
         };
 }
示例#29
0
        protected void Button1_Click(object sender, EventArgs e)
        {
            System.Web.HttpFileCollection _file1 = System.Web.HttpContext.Current.Request.Files;


            int i = 90;

            i++;
        }
示例#30
0
        protected void btnSaveImageData_Click(object sender, System.EventArgs e)
        {
            string value     = this.RePlaceImg.Value;
            int    photoId   = System.Convert.ToInt32(this.RePlaceId.Value);
            string photoPath = GalleryHelper.GetPhotoPath(photoId);
            string a         = photoPath.Substring(photoPath.LastIndexOf("."));
            string b         = string.Empty;
            string text      = string.Empty;

            try
            {
                System.Web.HttpFileCollection files          = base.Request.Files;
                System.Web.HttpPostedFile     httpPostedFile = files[0];
                b = System.IO.Path.GetExtension(httpPostedFile.FileName);
                if (a != b)
                {
                    this.ShowMsg("上传图片类型与原文件类型不一致!", false);
                }
                else
                {
                    string str = Globals.ApplicationPath + HiContext.Current.GetStoragePath() + "/gallery";
                    text = photoPath.Substring(photoPath.LastIndexOf("/") + 1);
                    string text2         = value.Substring(value.LastIndexOf("/") - 6, 6);
                    string text3         = str + "/" + text2 + "/";
                    int    contentLength = httpPostedFile.ContentLength;
                    string path          = base.Request.MapPath(text3);
                    //修改1
                    System.IO.DirectoryInfo directoryInfo = new System.IO.DirectoryInfo(path);
                    if (!directoryInfo.Exists)
                    {
                        directoryInfo.Create();
                    }
                    if (!ResourcesHelper.CheckPostedFile(httpPostedFile))
                    {
                        this.ShowMsg("文件上传的类型不正确!", false);
                    }
                    else
                    {
                        if (contentLength >= 2048000)
                        {
                            this.ShowMsg("图片文件已超过网站限制大小!", false);
                        }
                        else
                        {
                            httpPostedFile.SaveAs(base.Request.MapPath(text3 + text));
                            GalleryHelper.ReplacePhoto(photoId, contentLength);
                            this.CloseWindow();
                        }
                    }
                }
            }
            catch
            {
                this.ShowMsg("替换文件错误!", false);
            }
        }
示例#31
0
        /// <summary> Initializes a new instance of the <see cref="Request" /> class </summary>
        /// <param name="get">The get</param>
        /// <param name="post">The post</param>
        /// <param name="cookies">The cookies</param>
        /// <param name="files">The files</param>
        /// <param name="server">The server</param>
        /// <param name="headers">The headers</param>
        public Request(NameValueCollection get = null, NameValueCollection post = null, HttpCookieCollection cookies = null, HttpFileCollection files = null, NameValueCollection server = null, NameValueCollection headers = null)
        {
            this.get = get ?? new NameValueCollection();
            this.post = post ?? new NameValueCollection();
            this.cookies = cookies ?? new HttpCookieCollection();
            this.files = files;
            this.server = server ?? new NameValueCollection();

            this.headers = headers ?? this.ReadHeaders();
        }
        public ActionResult GuardaDocumento()
        {
            var helper = new ArchivoHelper();

            try
            {
                var    id       = Convert.ToInt32(System.Web.HttpContext.Current.Request.Form["id"].ToString());
                var    tipo     = Convert.ToInt32(System.Web.HttpContext.Current.Request.Form["tipo"].ToString());
                string sPath    = "";
                string temppath = "~/Documentos/" + id.ToString() + "/";
                sPath = System.Web.Hosting.HostingEnvironment.MapPath(temppath);
                System.Web.HttpFileCollection hfc = System.Web.HttpContext.Current.Request.Files;

                sPath = System.Web.Hosting.HostingEnvironment.MapPath(temppath);
                System.Web.HttpPostedFile hpf = hfc[0];

                var indicie = hpf.FileName.Split('.').Length - 1;
                var ext     = "." + hpf.FileName.Split('.')[indicie];

                if (!helper.ExtensionValida(ext.Substring(1, ext.Length - 1)))
                {
                    return(Json(new { Resultado = false, Error = "El tipo de archivo no es admitido." }));
                }

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


                var _nombrearchivo = DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString() + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString() + DateTime.Now.Millisecond.ToString() + ext;


                hpf.SaveAs(sPath + hpf.FileName.Replace(ext, _nombrearchivo));

                DocumentosClienteRepository dac = new DocumentosClienteRepository();
                ExDocumentos doc = new ExDocumentos();
                doc.usuario_creacion     = "admin";
                doc.usuario_modificacion = "admin";
                //doc.ruta_local = sPath + hpf.FileName.Replace(ext, _nombrearchivo);
                doc.ruta_local         = @"\Documentos\" + id.ToString() + "\\" + hpf.FileName.Replace(ext, _nombrearchivo);
                doc.id_precliente      = id;
                doc.id_documento       = tipo;
                doc.fecha_modificacion = DateTime.Now;
                doc.fecha_creacion     = DateTime.Now;
                doc.activo             = true;
                dac.guardaDocumento(doc);
                return(Json(doc.ruta_local));
            }
            catch (Exception ex)
            {
                Response.StatusCode = (int)HttpStatusCode.InternalServerError;
                return(Json(new { Resultado = false, Error = ex.Message }));
            }
        }
示例#33
0
        private ProfileModels updateModel()
        {
            ProfileModels profilemodel = new ProfileModels();
            string        sPath        = "";

            //Server File Path
            sPath = System.Web.Hosting.HostingEnvironment.MapPath("~/Uploads/");

            try
            {
                //retreive the image from Request
                System.Web.HttpFileCollection hfc = System.Web.HttpContext.Current.Request.Files;
                HttpRequest request = HttpContext.Current.Request;

                if (hfc.Count > 0)
                {
                    System.Web.HttpPostedFile hpf = hfc[0];

                    if (hpf.ContentLength > 0)
                    {
                        // save the file in the directory
                        hpf.SaveAs(sPath + Path.GetFileName(hpf.FileName));

                        //Read the bytes of the file
                        byte[] imageData = File.ReadAllBytes(sPath + Path.GetFileName(hpf.FileName));

                        //bind to profilePicture model
                        profilemodel.ProfilePicture = imageData;

                        //Finally delete the saved file as we are saving it to the database
                        File.Delete(sPath + Path.GetFileName(hpf.FileName));
                    }
                }
                if (request.Form.Keys.Count > 0)
                {
                    profilemodel.AboutMe      = request.Form["AboutMe"];
                    profilemodel.firstName    = request.Form["firstName"];
                    profilemodel.lastName     = request.Form["lastName"];
                    profilemodel.DOB          = request.Form["DOB"];
                    profilemodel.Mobile       = request.Form["Mobile"];
                    profilemodel.Organization = request.Form["Organization"];
                    profilemodel.Country      = request.Form["Country"];
                    profilemodel.AboutMe      = request.Form["AboutMe"];
                    profilemodel.Sex          = request.Form["Sex"];
                    profilemodel.EmailId      = request.Form["EmailId"];
                    profilemodel.City         = request.Form["City"];
                    profilemodel.Website      = request.Form["Website"];
                }
            }
            catch (Exception exception)
            {
                throw new Exception(exception.ToString());
            }
            return(profilemodel);
        }
示例#34
0
    protected void Button1_Click(object sender, EventArgs e)
    {
        if (ViewState["STATE"].ToString() == "N" && "".Equals(HiddenField1.Value.Trim()))
        {
            Tunnel.Common.Message.back("请选择附件");
            return;
        }
        System.Web.HttpFileCollection uploadFiles = Request.Files;
        System.Web.HttpPostedFile     theFile;
        for (int i = 0; i < uploadFiles.Count; i++)
        {
            theFile = uploadFiles[i];
            if (Convert.ToDouble(theFile.ContentLength) / 1024 / 1024 > 10)
            {
                Tunnel.Common.Message.back("附件大小不能大于10MB");
                return;
            }
            else
            {
                continue;
            }
        }
        //上传附件并新增数据
        if (Add(UpFiles()))
        {
            Response.Redirect("Produce_Manage.aspx?type=" + proType + "&name=" + Server.UrlEncode(Request.QueryString["name"].ToString().Trim()));
        }
        else
        {
            Tunnel.Common.Message.back("附件上传失败");
            return;
        }

        //string[] strFile = HiddenField1.Value.Trim().Split(new Char[]{','},StringSplitOptions.RemoveEmptyEntries);
        //for (int i = 0; i < strFile.Length; i++)
        //{
        //    if (UpFiles(m_ProduceModel))
        //    {
        //        if (Add())
        //        {
        //            Response.Redirect("Produce_Manage.aspx?type="+proType+"&name"+Request.QueryString["name"].ToString().Trim());
        //        }
        //        else
        //        {
        //            Tunnel.Common.Message.back("附件上传失败");
        //            return;
        //        }
        //    }
        //    else
        //    {
        //        Tunnel.Common.Message.back("附件上传失败");
        //        return;
        //    }
        //}
    }
示例#35
0
 /// <summary>
 /// 保存所有文件
 /// </summary>
 /// <param name="files">文件对象</param>
 /// <param name="content">内容(如果有的话)</param>
 /// <param name="explain">阐述(如果有的话)</param>
 /// <param name="wmPoint">水印位置</param>
 /// <param name="wmPath">水印文件路径</param>
 /// <returns>附件列表</returns>
 public string SaveAs(HttpFileCollection files, ref string content, ref string explain, int wmPoint, string wmPath)
 {
     string result = string.Empty;
     for (int i = 0; i < files.Count; i++)
     {
         if (files[i] != null && files[i].ContentLength > 0)
         {
             FileInfo tempFileInfo = new FileInfo(files[i].FileName);
             if (!string.IsNullOrEmpty(tempFileInfo.Extension))
             {
                 //保存文件
                 string saveFolder = "Attach/" + DateTime.Now.ToString("yyyyMM") + "/";
                 string savePath = saveFolder + DateTime.Now.ToString("ddHHmmss") + "-" + tempFileInfo.Name;
                 if (!Directory.Exists(Path.Combine(SiteCfg.Router, saveFolder))) { Directory.CreateDirectory(Path.Combine(SiteCfg.Router, saveFolder)); }
                 if (wmPoint > 0 && File.Exists(wmPath) && (tempFileInfo.Extension.ToLower() == ".bmp" || tempFileInfo.Extension.ToLower() == ".gif" || tempFileInfo.Extension.ToLower() == ".jpg" || tempFileInfo.Extension.ToLower() == ".png"))
                 {
                     files[i].SaveAs(Path.Combine(SiteCfg.Router, "Common/Temp/" + tempFileInfo.Name));
                     new SiteWatermark().HandleImage(Path.Combine(SiteCfg.Router, "Common/Temp/" + tempFileInfo.Name), Path.Combine(SiteCfg.Router, savePath), wmPath, wmPoint, true);
                 }
                 else { files[i].SaveAs(Path.Combine(SiteCfg.Router, savePath)); }
                 //创建附件信息
                 AttachmentItem attVal = new AttachmentItem();
                 attVal.Name = tempFileInfo.Name;
                 attVal.Path = savePath;
                 attVal.Type = files[i].ContentType;
                 attVal.Size = files[i].ContentLength;
                 int tmpId = new AttachmentData(conn).InsertAttachment(attVal);
                 result += string.Format("{0},", tmpId);
                 //判断文件
                 string replaceTag = string.Format("[LocalUpload_{0}]", i);
                 string replaceImgHtml = string.Format("<span class=\"sysAttachImage\"><img src=\"{0}\"/></span>", SiteCfg.Path + savePath);
                 string replaceFileHtml = string.Format("<span class=\"sysAttachDownload\"><a href=\"{0}\">{1}</a></span>", SiteCfg.Path + savePath, SiteDat.GetLan("ClickDown"));
                 string replaceMusicHtml = string.Format("<span class=\"sysAttachMusic\"><embed type=\"application/x-shockwave-flash\" classid=\"clsid:d27cdb6e-ae6d-11cf-96b8-4445535400000\" src=\"{0}Common/Editor/player.swf?soundFile={1}&amp;t=swf\" wmode=\"opaque\" quality=\"high\" menu=\"false\" play=\"true\" loop=\"true\" allowfullscreen=\"true\" height=\"26\" width=\"300\" /></span>", SiteCfg.Path, SiteFun.UrlEncode(SiteCfg.Path + savePath));
                 //格式化内容数据
                 if (tempFileInfo.Extension.ToUpper() == ".BMP" || tempFileInfo.Extension.ToUpper() == ".GIF" || tempFileInfo.Extension.ToUpper() == ".JPG" || tempFileInfo.Extension.ToUpper() == ".PNG")
                 {
                     if (!string.IsNullOrEmpty(content)) { content = content.Replace(replaceTag, replaceImgHtml); }
                     if (!string.IsNullOrEmpty(explain)) { explain = explain.Replace(replaceTag, replaceImgHtml); }
                 }
                 else if (tempFileInfo.Extension.ToUpper() == ".MP3")
                 {
                     if (!string.IsNullOrEmpty(content)) { content = content.Replace(replaceTag, replaceMusicHtml); }
                     if (!string.IsNullOrEmpty(explain)) { explain = explain.Replace(replaceTag, replaceMusicHtml); }
                 }
                 else
                 {
                     if (!string.IsNullOrEmpty(content)) { content = content.Replace(replaceTag, replaceFileHtml); }
                     if (!string.IsNullOrEmpty(explain)) { explain = explain.Replace(replaceTag, replaceFileHtml); }
                 }
             }
         }
     }
     if (result.Length > 0) { result = result.Remove(result.Length - 1); }
     return result;
 }
示例#36
0
 /// <summary>
 /// 判断用户是否上传了文件
 /// </summary>
 /// <param name="files">上传文件组</param>
 /// <returns>如果用记上传了文件返回true, 反之返回false</returns>
 public static bool IsFileUpload(HttpFileCollection files)
 {
     if (files.Count != 0)
     {
         return true;
     }
     else
     {
         return false;
     }
 }
示例#37
0
        public Response UploadFilesDemo()
        {
            System.Web.HttpFileCollection hfc = System.Web.HttpContext.Current.Request.Files;
            //BinaryReader reader = new BinaryReader(file.InputStream);

            Response r = new Response();

            r.Status  = "ok";
            r.Message = "File name ok";
            return(r);
        }
 public void Post([FromUri] string imageSrc)
 {
     System.Web.HttpFileCollection httpRequest = System.Web.HttpContext.Current.Request.Files;
     for (int i = 0; i <= httpRequest.Count - 1; i++)
     {
         System.Web.HttpPostedFile postedfile = httpRequest[i];
         if (postedfile.ContentLength > 0)
         {
         }
     }
 }
示例#39
0
        public dynamic UploadImages()
        {
            string      type    = Fun.Form("type");
            HttpRequest request = System.Web.HttpContext.Current.Request;
            Upload      Up      = new Upload();

            System.Web.HttpFileCollection uploadFiles = request.Files;//获取需要上传的文件
            string fileUrl = Up.SaveAs("img", uploadFiles[0], uploadFiles[0].FileName, type);

            return(fileUrl);
        }
示例#40
0
        /// <summary>
        ///     上传文件
        /// </summary>
        /// <param name="files">获取要上传的文件</param>
        /// <param name="filePath">要保存的文件路径,</param>
        /// <param name="lstFileType">允许上传的文件类型,大小,单位为KB,Size=0表示无任何限制</param>
        /// <param name="saveType">保存方式:1:按时间取名</param>
        public List<stuUpLoadFile> Upload(HttpFileCollection files, string filePath,
                                          SaveType saveType = SaveType.DateTime,
                                          List<stuUpLoadFileType> lstFileType = null)
        {
            var lstUpLoadFile = new List<stuUpLoadFile>();
            foreach (HttpPostedFile file in files)
            {
                lstUpLoadFile.Add(Upload(file, filePath, saveType, lstFileType));
            }

            return lstUpLoadFile;
        }
 public bool PerformAddOperation(string commandName, InformationSourceCollection sources, string requesterLocation, HttpFileCollection files)
 {
     if(ImageGroupTitle == "")
         throw new InvalidDataException("Image group title is mandatory");
     //IInformationObject container = sources.GetDefaultSource().RetrieveInformationObject();
     ImageGroup imageGroup = ImageGroup.CreateDefault();
     VirtualOwner owner = VirtualOwner.FigureOwner(this);
     imageGroup.SetLocationAsOwnerContent(owner, imageGroup.ID);
     imageGroup.Title = ImageGroupTitle;
     StorageSupport.StoreInformationMasterFirst(imageGroup, owner, true);
     DefaultViewSupport.CreateDefaultViewRelativeToRequester(requesterLocation, imageGroup, owner);
     return true;
 }
示例#42
0
		public void PopulateTree(CompositeNode root, HttpFileCollection fileCollection)
		{
			foreach (String key in fileCollection.Keys)
			{
				if (key == null) continue;

				HttpPostedFile value = fileCollection.Get(key);

				if (value == null) continue;

				ProcessNode(root, typeof (HttpPostedFile), key, value);
			}
		}
示例#43
0
 /// <summary>
 /// Uploads the file.
 /// </summary>
 /// <param name="files">The files.</param>
 /// <param name="imagePath">The image path.</param>
 /// <returns></returns>
 public static bool UploadFile(HttpFileCollection files, string imagePath)
 {
     for (int i = 0; i < files.Count; i++)
     {
         if (0 >= files[i].ContentLength) continue;
         int lastIndex = files[i].FileName.LastIndexOf("\\");
         string fileName = files[i].FileName;
         if (-1 != lastIndex)
             fileName = files[i].FileName.Substring(files[i].FileName.LastIndexOf("\\"));
         files[i].SaveAs(imagePath + fileName);
     }
     return true;
 }
示例#44
0
        /// <summary>
        /// 判断上传文件组里的文件大小是否超过最大值
        /// </summary>
        /// <param name="files">上传的文件组</param>
        /// <returns>超过最大值返回false,否则返回true.</returns>
        public static bool IsAllowedLengthForFiles(HttpFileCollection files)
        {
            for (int i = 0; i < files.Count; i++)
            {
                HttpPostedFile file = files[i];

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

            return true;
        }
        // This copy constructor is used by the granular request validation feature. Since these collections are immutable
        // once created, it's ok for us to have two collections containing the same data.
        internal HttpFileCollection(HttpFileCollection col)
            : this() {

            // We explicitly don't copy validation-related fields, as we want the copy to "reset" validation state.

            // Copy the file references from the original collection into this instance
            for (int i = 0; i < col.Count; i++) {
                ThrowIfMaxHttpCollectionKeysExceeded();
                string key = col.BaseGetKey(i);
                object value = col.BaseGet(i);
                BaseAdd(key, value);
            }

            IsReadOnly = col.IsReadOnly;
        }
示例#46
0
 public bool PerformAddOperation(string commandName, InformationSourceCollection sources, string requesterLocation, HttpFileCollection files)
 {
     if(CategoryName == "")
         throw new InvalidDataException("Category name is mandatory");
     Category category = new Category();
     VirtualOwner owner = VirtualOwner.FigureOwner(this);
     category.SetLocationAsOwnerContent(owner, category.ID);
     category.CategoryName = CategoryName;
     StorageSupport.StoreInformationMasterFirst(category, owner, true);
     //DefaultViewSupport.CreateDefaultViewRelativeToRequester(requesterLocation, category, owner);
     //BlogContainer blogContainer = BlogContainer.RetrieveFromOwnerContent(owner, "default");
     //blogContainer.AddNewBlogPost(blog);
     //StorageSupport.StoreInformation(blogContainer);
     CategoryName = "";
     return true;
 }
 public bool PerformAddOperation(string commandName, InformationSourceCollection sources, string requesterLocation, HttpFileCollection files)
 {
     if (ActivityName == "")
         throw new InvalidDataException("Activity name is mandatory");
     Activity activity = Activity.CreateDefault();
     VirtualOwner owner = VirtualOwner.FigureOwner(this);
     activity.SetLocationAsOwnerContent(owner, activity.ID);
     activity.ActivityName = ActivityName;
     activity.ReferenceToInformation.Title = activity.ActivityName;
     activity.ReferenceToInformation.URL = DefaultViewSupport.GetDefaultViewURL(activity);
     StorageSupport.StoreInformationMasterFirst(activity, owner, true);
     DefaultViewSupport.CreateDefaultViewRelativeToRequester(requesterLocation, activity, owner);
     //ActivitySummaryContainer summaryContainer = ActivitySummaryContainer.RetrieveFromOwnerContent(owner, "default");
     //summaryContainer.AddNewActivity(activity);
     //StorageSupport.StoreInformation(summaryContainer);
     return true;
 }
示例#48
0
 public bool PerformAddOperation(string commandName, InformationSourceCollection sources, string requesterLocation, HttpFileCollection files)
 {
     if(GroupName == "")
         throw new InvalidDataException("Group name must be given");
     //throw new NotImplementedException("Old implementation not converted to managed group structures");
     //AccountContainer container = (AccountContainer) sources.GetDefaultSource(typeof(AccountContainer).FullName).RetrieveInformationObject();
     VirtualOwner owner = VirtualOwner.FigureOwner(this);
     if(owner.ContainerName != "acc")
         throw new NotSupportedException("Group creation only supported from account");
     string accountID = owner.LocationPrefix;
     TBRAccountRoot accountRoot = TBRAccountRoot.RetrieveFromDefaultLocation(accountID);
     TBAccount account = accountRoot.Account;
     if (account.Emails.CollectionContent.Count == 0)
         throw new InvalidDataException("Account needs to have at least one email address to create a group");
     CreateGroup.Execute(new CreateGroupParameters { AccountID = accountID, GroupName = this.GroupName });
     this.GroupName = "";
     return true;
 }
示例#49
0
 public bool PerformAddOperation(string commandName, InformationSourceCollection sources, string requesterLocation, HttpFileCollection files)
 {
     if(Title == "")
         throw new InvalidDataException("Blog title is mandatory");
     Blog blog = Blog.CreateDefault();
     VirtualOwner owner = VirtualOwner.FigureOwner(this);
     blog.SetLocationAsOwnerContent(owner, blog.ID);
     blog.Title = Title;
     blog.ReferenceToInformation.Title = blog.Title;
     blog.ReferenceToInformation.URL = blog.RelativeLocation; // DefaultViewSupport.GetDefaultViewURL(blog);
     blog.Published = DateTime.Now;
     StorageSupport.StoreInformationMasterFirst(blog, owner, true);
     //DefaultViewSupport.CreateDefaultViewRelativeToRequester(requesterLocation, blog, owner);
     //BlogContainer blogContainer = BlogContainer.RetrieveFromOwnerContent(owner, "default");
     //blogContainer.AddNewBlogPost(blog);
     //StorageSupport.StoreInformation(blogContainer);
     Title = "";
     return true;
 }
示例#50
0
文件: UploadFile.cs 项目: uwitec/O2O
        /// <summary>
        ///  ��֤�ļ��ϴ���ʽ
        /// </summary>
        /// <param name="files"> files ���� </param>
        /// <param name="controlName">�ؼ�nameֵ</param>
        /// <param name="allowExtensions">�ϴ��ļ���ʽ ��[".jpg","gif"]</param>
        /// <param name="allowExtensions">�ļ��ϴ���С���ƣ���λΪM��Ϊnull��Ĭ��</param>
        /// <param name="allowExtensions">��֤������Ϣ</param>
        /// <returns></returns>
        public static bool CheckFileType(HttpFileCollection files, string controlName, string[] allowExtensions, int? fileSize, out string msg)
        {
            bool fileAllow = false;
            msg = "";
            if (fileSize == null) { fileSize = 5; };
            if (files != null && files.Count > 0)
            {
                for (int i = 0; i < files.Count; i++)
                {
                    if (files.GetKey(i).ToString() == controlName)
                    {
                        if (files[i] != null && files[i].FileName.Trim() == "")
                        {
                            return true;
                        }

                        if (files[i].ContentLength / 1024 / 1024 > fileSize)
                        {
                            msg = files[i].FileName + " �ļ������޷��ϴ�!";
                            return false;
                        }
                        string fileExtension = System.IO.Path.GetExtension(files[i].FileName).ToLower();
                        for (int j = 0; j < allowExtensions.Length; j++)
                        {
                            if (fileExtension.ToLower() == allowExtensions[j].ToLower())
                            {
                                fileAllow = true;
                            }
                        }
                    }
                }
            }
            if (!fileAllow)
            {
                msg = "�ļ���ʽ����ȷ!";
            }
            else
            {
                msg = "��֤�ɹ�!";
            }
            return fileAllow;
        }
示例#51
0
 private string saveFile(HttpFileCollection files)
 {
     if (files == null)
         return "";
     if (files.Count < 1)
         return "";
     if (files[0].ContentLength < 1)
     {
         return "";
     }
     string fileS = files[0].FileName.Substring(files[0].FileName.LastIndexOf('.'));
     string fileSaveName = Commons.StringHelper.getDateString()+fileS;
     string strPath=Commons.WebPage.PageRequest.getRootMapPath() + "ProductsImage";
     if (!Directory.Exists(strPath))
     {
         Directory.CreateDirectory(strPath);
     }
     files[0].SaveAs(strPath + "\\" + fileSaveName);
     return  fileSaveName;
 }
示例#52
0
        /// <summary>
        /// Saving new file attachments.
        /// </summary>
        /// <param name="fileCollection">Collection of posted files.</param>
        /// <param name="currentNews">News for eorking.</param>
        public void SaveNewsAttachmentFiles(HttpFileCollection fileCollection, News currentNews)
        {
            for (int i = 0; i < fileCollection.Count; i++)
            {
                HttpPostedFile file = fileCollection[i];

                if (file.FileName == null ||
                    String.IsNullOrEmpty(file.FileName))
                    continue;

                String uniqueName = Guid.NewGuid() + "_" + GetFileName(file.FileName);

                // добавляем неприкрепленный аттачмент в БД
                NewsAttachment attach = new NewsAttachment();
                attach.FileName = uniqueName;

                SaveFile(file, uniqueName);
                currentNews.Attachments.Add(attach);
            }
        }
        public void SaveUploadedFile(HttpFileCollection httpFileCollection)
        {
            bool isSavedSuccessfully = true;
            string fName = "";
            foreach (string fileName in httpFileCollection)
            {
                HttpPostedFile file = httpFileCollection.Get(fileName);
                //Save file content goes here
                fName = file.FileName;
                if (file != null && file.ContentLength > 0)
                {

                    var originalDirectory = new DirectoryInfo(string.Format("{0}Images\\WallImages", Server.MapPath(@"\")));

                    string pathString = System.IO.Path.Combine(originalDirectory.ToString(), "imagepath");

                    var fileName1 = Path.GetFileName(file.FileName);


                    bool isExists = System.IO.Directory.Exists(pathString);

                    if (!isExists)
                        System.IO.Directory.CreateDirectory(pathString);

                    var path = string.Format("{0}\\{1}", pathString, file.FileName);
                    file.SaveAs(path);

                }

            }

            //if (isSavedSuccessfully)
            //{
            //    return Json(new { Message = fName });
            //}
            //else
            //{
            //    return Json(new { Message = "Error in saving file" });
            //}
        }
示例#54
0
        public static void UploadFiles(HttpFileCollection files, NameValueCollection form)
        {
            //single upload
            if (files.Count == 1 && files.AllKeys.First() != null)
            {
                HttpPostedFile file = files[files.AllKeys.First()];

                if (file != null)
                {
                    string filename = file.FileName;
                    if (form["filename"] != null)
                    {
                        filename = Path.GetFileName(form["filename"]);
                    }

                    var fileSavePath = Path.Combine(ImagePath(), filename);
                    file.SaveAs(fileSavePath);

                }
                
            }
            //multi upload
            else 
            {
                foreach (String key in files.AllKeys)
                {
                    if (files[key].ContentLength > 0)
                    {
                        var fileSavePath = Path.Combine(ImagePath(), files[key].FileName);
                        files[key].SaveAs(fileSavePath);
                    }

                }

            }
        }
 public HttpFileCollectionWrapper(HttpFileCollection httpFileCollection)
 {
 }
示例#56
0
文件: IO.CS 项目: yodfz/PandaClass
            public static String UpLoadFile (HttpFileCollection Files, String Floder, String FileType, int FileSize)
            {
                String FileName = Files [0].FileName.ToString();
                int _FileSize = Files [0].ContentLength;
                FileName = FileName.Substring(FileName.LastIndexOf("."), FileName.Length - FileName.LastIndexOf("."));
                Random X = new Random();
                Floder = Floder + DateTime.Now.ToString("/yyyyMMdd/MMdd/");
                CreateDiretory(Floder);
                Floder += DateTime.Now.ToString("yyyyMMddhhmmss") + X.Next(0, 99999) + FileName;
                FileName = FileName.Replace(".", "");
                if (FileType.ToUpper().IndexOf(FileName.ToUpper()) > -1)
                {
                    if (_FileSize <= FileSize)
                    {
                        Files [0].SaveAs(HttpContext.Current.Server.MapPath(Floder));
                        return Floder;
                    }
                    else
                    {
                        return "文件超出大小";
                    }
                }
                else
                {
                    return "类型错误";
                }


            }
        public void UploadWholeFileEx(HttpFileCollection files, List<FilesStatus> status)
        {
            for (var i = 0; i< files.Count; i++)
            {
                HttpPostedFile file = files[i];

                status.Add(UploadSingleFile(file));
            }
        }
示例#58
0
 private void ValidatePostedFileCollection(HttpFileCollection col) {
     if (GranularValidationEnabled) {
         // Granular request validation is enabled - validate collection entries only as they're accessed.
         col.EnableGranularValidation((key, value) => ValidateString(value, "filename", RequestValidationSource.Files));
     }
     else {
         // Granular request validation is disabled - eagerly validate all collection entries.
         for (int i = 0; i < col.Count; i++) {
             string filename = col[i].FileName;
             ValidateString(filename, "filename", RequestValidationSource.Files);
         }
     }
 }
示例#59
0
        // Populates the Files property but does not hook up validation.
        internal HttpFileCollection EnsureFiles() {
            if (_files == null) {
                if (_readEntityBodyMode == ReadEntityBodyMode.Bufferless)
                    throw new HttpException(SR.GetString(SR.Incompatible_with_get_bufferless_input_stream));

                _files = new HttpFileCollection();

                if (_wr != null)
                    FillInFilesCollection();
            }

            return _files;
        }
		public UploadEventArgs(HttpFileCollection files, NameValueCollection form)
		{
			this.Files = files;
			this.Response = String.Empty;
			this.Form = form;
		}