Esempio n. 1
2
        /// <summary>
        /// 文件上传
        /// </summary>
        /// <param name="postedFile">文件流</param>
        /// <param name="isWater">是否返回文件原名称</param>
        /// <returns>服务器文件路径</returns>
        public ResultExcelImport FileSaveAs(HttpPostedFile postedFile)
        {
            try
            {
                string fileExt = postedFile.FileName.Substring(postedFile.FileName.LastIndexOf(".", System.StringComparison.Ordinal) + 1); //文件扩展名,不含“.”
                string originalFileName = postedFile.FileName.Substring(postedFile.FileName.LastIndexOf(@"\", System.StringComparison.Ordinal) + 1); //取得文件原名
                string fileName = Utils.GetRamCode() + "." + fileExt; //随机文件名
                string dirPath = ConfigurationManager.AppSettings["UploadExcel"]; //上传目录相对路径

                //检查文件扩展名是否合法
                if (!CheckFileExt(fileExt))
                {
                    return new ResultExcelImport {Success = false, MsgContent = "不允许上传" + fileExt + "类型的文件!"};
                }

                //获得要保存的文件路径
                string serverFileName = dirPath + fileName;
                string returnFileName = serverFileName;
                //物理完整路径
               // string toFileFullPath = Utils.GetMapPath(dirPath);
                //检查有该路径是否就创建
                if (!Directory.Exists(dirPath))
                {
                    Directory.CreateDirectory(dirPath);
                }
                //保存文件
                postedFile.SaveAs(dirPath + fileName);
                return new ResultExcelImport { Success = true, MsgContent = returnFileName };

            }
            catch
            {
                return new ResultExcelImport { Success = false, MsgContent = "上传过程中发生意外错误!" };
            }
        }
Esempio n. 2
0
        /// <summary>
        /// 批量保存文件
        /// </summary>
        /// <param name="AbsoluteFilePath">文件保存路径</param>
        /// <returns>
        ///		0:上传文件成功
        ///		1:上传的文件超过指定大小
        ///		2:上传的文件格式不在指定的后缀名列表中
        ///		3:上传的文件没有后缀名
        ///		4:保存文件出错
        ///		5:没有发现上传的文件
        ///</returns>
        public int FilesNewNameSave(string AbsoluteFilePath)
        {
            System.Web.HttpFileCollection files = System.Web.HttpContext.Current.Request.Files;
            string tmpFileExt = _UploadFileExt;

            string[] strFileExt = tmpFileExt.Split(',');
            if (files.Count < 1)
            {
                files = null;
                return(5);//没有发现上传文件;
            }
            //处理多文件
            for (int i = 0; i < files.Count; i++)
            {
                System.Web.HttpPostedFile file = files[i];
                //判断文件大小
                if (file.ContentLength > _UpFolderSize * 1024)
                {
                    return(1);
                }
                //检验后缀名,无后缀名的不做处理
                if (file.FileName != String.Empty)
                {
                    if (IsStringExists(System.IO.Path.GetExtension(file.FileName).ToLower().Trim(), strFileExt) == false)
                    {
                        return(2);
                    }
                    //保存文件
                    try
                    {
                        if (AbsoluteFilePath.LastIndexOf("\\") == AbsoluteFilePath.Length)
                        {
                            CreateDirectory(AbsoluteFilePath);
                            file.SaveAs(AbsoluteFilePath + TimeFileName(System.IO.Path.GetExtension(file.FileName)));
                        }
                        else
                        {
                            CreateDirectory(AbsoluteFilePath);
                            file.SaveAs(AbsoluteFilePath + "\\" + TimeFileName(System.IO.Path.GetExtension(file.FileName)));
                        }
                    }
                    //catch(Exception e1)
                    catch
                    {
                        //throw new Exception(e1.Source + e1.Message);
                        return(4);
                    }
                }
            }
            files = null;
            return(0);
        }
Esempio n. 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));
        }
Esempio n. 4
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;
            }
        }
 public string SavePhoto(HttpPostedFile imageFile)
 {
     var path = @"~/Images/users_pic";
     var filename = string.Format("{0}/{1}", path, imageFile.FileName);
     imageFile.SaveAs(System.Web.Hosting.HostingEnvironment.MapPath(filename));
     return filename;
 }
Esempio n. 6
0
 private void UploadImage()
 {
     try
     {
         System.Web.HttpPostedFile file = System.Web.HttpContext.Current.Request.Files["Filedata"];
         string str  = System.DateTime.Now.ToString("yyyyMMddHHmmss_ffff", System.Globalization.DateTimeFormatInfo.InvariantInfo);
         string str2 = System.Web.HttpContext.Current.Request["uploadpath"];
         string str3 = str + System.IO.Path.GetExtension(file.FileName);
         if (string.IsNullOrEmpty(str2))
         {
             str2 = Globals.GetVshopSkinPath(null) + "/images/ad/";
             str3 = "imgCustomBg" + System.IO.Path.GetExtension(file.FileName);
             string[] files = System.IO.Directory.GetFiles(Globals.MapPath(str2), "imgCustomBg.*");
             for (int i = 0; i < files.Length; i++)
             {
                 string str4 = files[i];
                 System.IO.File.Delete(str4);
             }
         }
         if (!System.IO.Directory.Exists(Globals.MapPath(str2)))
         {
             System.IO.Directory.CreateDirectory(Globals.MapPath(str2));
         }
         file.SaveAs(Globals.MapPath(str2 + str3));
         System.Web.HttpContext.Current.Response.Write(str2 + str3);
     }
     catch (System.Exception)
     {
         System.Web.HttpContext.Current.Response.Write("服务器错误");
         System.Web.HttpContext.Current.Response.End();
     }
 }
Esempio n. 7
0
        private string SaveFile(string Folder, string tmbname, System.Web.HttpPostedFile hpf, Boolean isImageFile, Boolean isPdfFile, string comp_code)
        {
            string     retval    = "";
            string     FileName  = "";
            string     thumbNail = "";
            imageTools tools     = new imageTools();

            try
            {
                Lib.CreateFolder(Folder);

                FileName = Path.Combine(Folder, Path.GetFileName(hpf.FileName));
                hpf.SaveAs(FileName);

                if (isImageFile)
                {
                    thumbNail = Path.Combine(Folder, tmbname);
                    tools.Save(FileName, thumbNail);
                }
                if (isPdfFile)
                {
                    thumbNail = Path.Combine(Folder, tmbname);
                    SavePdf2Image(FileName, thumbNail, comp_code);
                }
            }
            catch (Exception Ex)
            {
                retval = Ex.Message.ToString();
            }

            return(retval);
        }
Esempio n. 8
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);
        }
        public virtual string SaveFile(System.Web.HttpPostedFile file)
        {
            if (file == null || file.ContentLength <= 0)
            {
                return(null);
            }
            else
            {
                var fileName       = Path.GetFileName(file.FileName);
                var fileExt        = Path.GetExtension(file.FileName);
                var attachSavePath = System.Web.Configuration.WebConfigurationManager.AppSettings["attachSavePath"];

                if (string.IsNullOrEmpty(attachSavePath))
                {
                    return(null);
                }
                var relativeSavePath = Path.Combine(attachSavePath, Commons.ServerDateTime.ToString("yyyy-MM"));
                var abstractSavePath = HttpContext.Current.Server.MapPath(relativeSavePath);
                if (!Directory.Exists(abstractSavePath))
                {
                    Directory.CreateDirectory(abstractSavePath);
                }
                var saveName = Guid.NewGuid().ToString() + fileExt;
                file.SaveAs(Path.Combine(abstractSavePath, saveName));
                var relativeFileFullName = Path.Combine(relativeSavePath, saveName).Replace("\\", "/");
                // 保存进数据库的路径,去掉根目录符,方便以后扩展
                if (relativeFileFullName.StartsWith("~"))
                {
                    relativeFileFullName = relativeFileFullName.TrimStart('~');
                }

                return(relativeFileFullName);
            }
        }
Esempio n. 10
0
        public FileInfo SaveAs(string repositoryDir, HttpPostedFile postedFile, string saveFilename)
        {
            // ������ ������ ���� �����
            string folder	= RepositoryDirectory + "/" + repositoryDir;
            if( !Directory.Exists( folder ))
                Directory.CreateDirectory( folder );

            // {0} : Web.config �� ������ upload ����
            // {1} : �� ����
            // {2} : ���ϸ�

            string fileName;
            if (saveFilename == null)
                fileName	= Path.GetFileName(postedFile.FileName);
            else
                fileName	= saveFilename;

            string saveFullName	= string.Format("{0}/{1}/{2}",
                RepositoryDirectory,
                repositoryDir,
                fileName );

            postedFile.SaveAs(saveFullName);

            return new FileInfo( saveFullName );
        }
Esempio n. 11
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");
     }
 }
Esempio n. 12
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 static bool SaveImageToCustomPath(string imgpath, HttpPostedFile image)
        {
            bool isSuccess = true;
            if (image != null && image.ContentLength > 0)
            {
                try
                {

                    if (System.IO.File.Exists(imgpath))
                        System.IO.File.Delete(imgpath);
                    image.SaveAs(imgpath);
                }
                catch (Exception e)
                {
                    var trace = e.StackTrace;
                    isSuccess = false;
                }

            }
            else
            {
                isSuccess = false;
            }
            return isSuccess;
        }
Esempio n. 14
0
    /// <summary>
    /// 上传文件
    /// </summary>
    /// <param name="file">文件流</param>
    /// <param name="Folder">文件夹名字</param>
    /// <param name="fileExt">允许上传的文件名后缀(小写),用‘,’分隔</param>
    /// <param name="filename">返回的文件名</param>
    /// <returns></returns>
    public bool MakeThumbFile(System.Web.HttpPostedFile file, string Folder, string fileExt, ref string filename)
    {
        string FileName = DateTime.Now.ToString("yyyyMMddHHmmss") + Common.Number(4, false);

        if (file.ContentLength > 0)
        {
            System.IO.FileInfo _file = new System.IO.FileInfo(file.FileName);

            string _fileExt  = _file.Name.ToLower().Substring(_file.Name.LastIndexOf('.') + 1),
                   _fileName = FileName + "." + _fileExt,
                   _folder   = "../UploadFile/" + Folder + "/";

            string[] FileExt = fileExt.Split(',');
            if (!Common.ArrayIsContains(FileExt, _fileExt))
            {
                return(false);
            }
            else
            {
                filename = _fileName;
                FileUtils.CreateFile(_folder);
                string filePath = _folder + _fileName;
                file.SaveAs(Common.getAbsolutePath(filePath));
                return(true);
            }
        }
        else
        {
            return(false);
        }
    }
Esempio n. 15
0
 protected override void SaveAs(string uploadPath, string fileName, HttpPostedFile file)
 {
     file.SaveAs(uploadPath + fileName);
     ImageTools.MakeThumbnail(uploadPath + fileName, uploadPath + "T32X32_" + fileName, 0x20, 0x20, MakeThumbnailMode.HW, InterpolationMode.High, SmoothingMode.HighQuality);
     ImageTools.MakeThumbnail(uploadPath + fileName, uploadPath + "T130X130_" + fileName, 130, 130, MakeThumbnailMode.HW, InterpolationMode.High, SmoothingMode.HighQuality);
     ImageTools.MakeThumbnail(uploadPath + fileName, uploadPath + "T300X390_" + fileName, 300, 390, MakeThumbnailMode.Cut, InterpolationMode.High, SmoothingMode.HighQuality);
 }
Esempio n. 16
0
 public static void uploadFileControl(HttpPostedFile hpf, string savePath, string FileType, out string OutPath)
 {
     OutPath = string.Empty;
     if (hpf != null)
     {
         if (!string.IsNullOrEmpty(hpf.ToString()))
         {
             try
             {
                 string ext = System.IO.Path.GetExtension(hpf.FileName).ToLower();
                 if (!IsFileType(FileType, ext))
                 {
                     return;
                 }
                 string filename = Guid.NewGuid().ToString("N", System.Globalization.CultureInfo.InvariantCulture) + ext;//文件重命名_userId_CourseID
                 string pathStr = HttpContext.Current.Server.MapPath("/" + savePath);
                 if (!System.IO.Directory.Exists(pathStr))
                 {
                     System.IO.Directory.CreateDirectory(pathStr);
                 }
                 string path = "/" + savePath + "/" + filename;
                 hpf.SaveAs(HttpContext.Current.Server.MapPath(path));
                 OutPath = path;
             }
             catch (Exception)
             {
                 throw;
             }
         }
     }
     else
     {
         OutPath = string.Empty;
     }
 }
Esempio n. 17
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");
        }
Esempio n. 18
0
 /// <summary>
 ///  
 /// </summary>
 /// <param name="httpPostedFile">待传输文件</param>
 /// <param name="orderId"></param>
 /// <param name="imageType">图片类型</param>
 /// <returns></returns>
 public ImgInfo UploadFile(HttpPostedFile httpPostedFile, string uploadType, UploadFrom uploadFrom)
 {
     ImgInfo imgInfo = new ImgInfo();
     var fileName = ETS.Util.ImageTools.GetFileName(Path.GetExtension(httpPostedFile.FileName));
     imgInfo.FileName = fileName;
     imgInfo.OriginalName = httpPostedFile.FileName;
     int fileNameLastDot = fileName.LastIndexOf('.');
     //原图
     string rFileName = string.Format("{0}{1}", fileName.Substring(0, fileNameLastDot), Path.GetExtension(fileName));
     imgInfo.OriginFileName = rFileName;
     string saveDbFilePath;
     string saveDir = "";
     string basePath = Ets.Model.ParameterModel.Clienter.CustomerIconUploader.Instance.GetPhysicalPath(uploadFrom);
     string fullFileDir = ETS.Util.ImageTools.CreateDirectory(basePath, uploadType, out saveDbFilePath);
     imgInfo.FullFileDir = fullFileDir;
     imgInfo.SaveDbFilePath = saveDbFilePath;
     if (fullFileDir == "0")
     {
         imgInfo.FailRemark = "创建目录失败";
         return imgInfo;
     }
     var fullFilePath = Path.Combine(fullFileDir, rFileName);
     httpPostedFile.SaveAs(fullFilePath);
     var picUrl = saveDbFilePath + fileName;
     imgInfo.RelativePath = EnumUtils.GetEnumDescription(uploadFrom) + picUrl;
     imgInfo.PicUrl = ImageCommon.ReceiptPicConvert(uploadFrom, picUrl);
     return imgInfo;
 }
Esempio n. 19
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");
            }
        }
Esempio n. 20
0
        private void Page_Load(object sender, System.EventArgs e)
        {
            if (Request.Files.Count > 0)
            {
                System.Web.HttpPostedFile oFile = Request.Files.Get("FCKeditor_File");

                string    fileName           = oFile.FileName.Substring(oFile.FileName.LastIndexOf("\\") + 1);
                Hashtable ms                 = ModuleSettings.GetModuleSettings(portalSettings.ActiveModule);
                string    DefaultImageFolder = "default";
                if (ms["MODULE_IMAGE_FOLDER"] != null)
                {
                    DefaultImageFolder = ms["MODULE_IMAGE_FOLDER"].ToString();
                }
                else if (portalSettings.CustomSettings["SITESETTINGS_DEFAULT_IMAGE_FOLDER"] != null)
                {
                    DefaultImageFolder = portalSettings.CustomSettings["SITESETTINGS_DEFAULT_IMAGE_FOLDER"].ToString();
                }
                string sFileURL  = portalSettings.PortalFullPath + "/images/" + DefaultImageFolder + "/" + fileName;
                string sFilePath = Server.MapPath(sFileURL);

                oFile.SaveAs(sFilePath);

                Response.Write("<SCRIPT language=javascript>window.opener.setImage('" + sFileURL + "') ; window.close();</" + "SCRIPT>");
            }
        }
Esempio n. 21
0
        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="PostFile">FileUpLoad控件</param>
        /// <param name="UpLoadPath">传入文件保存路径,如:/UpLoadFile/excel/  返回文件绝对路径,如:/UpLoadFile/excel/a.xls</param>
        /// <param name="FileFormat">文件后缀,如:.xls</param>
        /// <returns>文件名称,如a.xls</returns>
        public static string UploadFile(HttpPostedFile PostFile, ref string UpLoadPath)
        {
            try
            {
                UpLoadPath += DateTime.Now.Year + "/" + DateTime.Now.Month;
                string savepath = HttpContext.Current.Server.MapPath(UpLoadPath);
                if (!Directory.Exists(savepath))
                {
                    Directory.CreateDirectory(savepath);
                }

                string ext = Path.GetExtension(PostFile.FileName);
                string filename = CreateIDCode() + ext;
                if (UpLoadPath.IndexOf(ext) == -1) //判断
                {
                    savepath = savepath + filename;
                }
                PostFile.SaveAs(savepath);

                UpLoadPath += filename;

                return filename;
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }
Esempio n. 22
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);
        }
Esempio n. 23
0
		public string fileSaveAs(HttpPostedFile _postedFile, int _isWater)
		{
			string result;
			try
			{
				string text = _postedFile.FileName.Substring(_postedFile.FileName.LastIndexOf(".") + 1);
				if (!this.CheckFileExt(this.fileType, text))
				{
					result = "{msg: 0, msbox: \"不允许上传" + text + "类型的文件!\"}";
				}
				else
				{
					if (this.fileSize > 0 && _postedFile.ContentLength > this.fileSize * 1024)
					{
						result = "{msg: 0, msbox: \"文件超过限制的大小啦!\"}";
					}
					else
					{
						string str = DateTime.Now.ToString("yyyyMMddHHmmssff") + "." + text;
						if (!this.filePath.StartsWith("/"))
						{
							this.filePath = "/" + this.filePath;
						}
						if (!this.filePath.EndsWith("/"))
						{
							this.filePath += "/";
						}
						string str2 = DateTime.Now.ToString("yyyyMMdd") + "/";
						this.filePath += str2;
						string text2 = this.filePath + str;
						string text3 = HttpContext.Current.Server.MapPath(this.filePath);
						if (!Directory.Exists(text3))
						{
							Directory.CreateDirectory(text3);
						}
						string filename = text3 + str;
						_postedFile.SaveAs(filename);
						if (this.isWatermark > 0 && _isWater == 1 && this.CheckFileExt("BMP|JPEG|JPG|GIF|PNG|TIFF", text))
						{
							switch (this.isWatermark)
							{
							case 1:
								ImageWaterMark.AddImageSignText(text2, this.filePath + str, this.textWater, this.waterStatus, this.waterQuality, this.textWaterFont, this.textFontSize);
								break;
							case 2:
								ImageWaterMark.AddImageSignPic(text2, this.filePath + str, this.imgWaterPath, this.waterStatus, this.waterQuality, this.waterTransparency);
								break;
							}
						}
						result = "{msg: 1, msbox: \"" + text2 + "\"}";
					}
				}
			}
			catch
			{
				result = "{msg: 0, msbox: \"上传过程中发生意外错误!\"}";
			}
			return result;
		}
Esempio n. 24
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));
        }
Esempio n. 25
0
 public UploadedFile HandleFile(HttpPostedFile postedFile)
 {
     var uploadedFile = new UploadedFile {Name = postedFile.FileName};
     uploadedFile.TempFilePathAbsolute.EnsureDirectoryExists();
     postedFile.SaveAs(uploadedFile.TempFilePathAbsolute);
     Files.Add(uploadedFile);
     return uploadedFile;
 }
Esempio n. 26
0
        public async Task <Tuple <bool, string> > SaveImages(MultipartFormDataStreamProvider multipartFormDataStreamProvider, System.Web.HttpFileCollection hfc, string fileUploadPath)
        {
            UploadImagesModel    uploadImagesModel = new UploadImagesModel();
            Tuple <bool, string> resTuple          = null;
            int saveImgStatus = -1;

            try
            {
                int iUploadedCnt = 0;
                var formData     = multipartFormDataStreamProvider.FormData;
                foreach (var prop in typeof(UploadImagesModel).GetProperties())
                {
                    var curVal = formData[prop.Name];

                    if (curVal != null && !string.IsNullOrEmpty(curVal))
                    {
                        prop.SetValue(uploadImagesModel, To(curVal, prop.PropertyType), null);
                    }
                }

                if (!Directory.Exists(InstitutionImagesPath + uploadImagesModel.UserID))
                {
                    Directory.CreateDirectory(InstitutionImagesPath + uploadImagesModel.UserID);
                }

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

                    if (hpf.ContentLength > 0)
                    {
                        if (!File.Exists(InstitutionImagesPath + uploadImagesModel.UserID + "\\" + Path.GetFileName(hpf.FileName)))
                        {
                            hpf.SaveAs(InstitutionImagesPath + uploadImagesModel.UserID + "\\" + Path.GetFileName(hpf.FileName));
                            iUploadedCnt = iUploadedCnt + 1;
                        }
                    }
                }

                using (SqlConnection cxn = new SqlConnection(_dcDb))
                {
                    var parameters = new DynamicParameters();
                    parameters.Add("@UserID", uploadImagesModel.UserID, DbType.Int32);
                    parameters.Add("@Description", uploadImagesModel.Description, DbType.String);
                    parameters.Add("@InstituteImgDocumentTable", CreateTable(uploadImagesModel, multipartFormDataStreamProvider.FileData.ToList(), fileUploadPath, ImageUrlPath + uploadImagesModel.UserID).AsTableValuedParameter());
                    parameters.Add("@CreatedBy", UserID, DbType.Int32);

                    saveImgStatus = await cxn.ExecuteScalarAsync <int>("dbo.Insert_InstituteImage", parameters, commandType : CommandType.StoredProcedure);
                }

                resTuple = Tuple.Create(true, "Created successfully");
            }
            catch (Exception ex)
            {
                ErrorLog.Write(ex);
            }
            return(resTuple);
        }
        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);
        }
Esempio n. 28
0
        /// <summary>
        /// 将上传文件加到某个批次
        /// </summary>
        /// <param name="curr_user"></param>
        /// <param name="postedFile"></param>
        /// <param name="batch_id"></param>
        /// <returns></returns>
        public static SysAttachment InsertAttachment(SysUserInfo curr_user, System.Web.HttpPostedFile postedFile, string batch_id)
        {
            string originalFilePath = postedFile.FileName;
            // save file
            // get user's site
            SysSiteList site_entity = AttachmentDataAccess.GetSysSiteList(curr_user.SiteSerial);

            if (site_entity == null)
            {
                throw new ApplicationException(string.Format("site [{0}] does not exists.", curr_user.SiteSerial));
            }

            // get site's upload path
            SysDocPath doc_path_entity = AttachmentDataAccess.GetSysDocPath(site_entity.CurrentUploadPathId);

            if (doc_path_entity == null)
            {
                throw new ApplicationException(string.Format("path_id [{0}]does not configed in db.", site_entity.CurrentUploadPathId));
            }
            string baseDir = doc_path_entity.DocPath;

            // get child dir
            DateTime dt_now  = DateTime.Now;
            string   subDir  = dt_now.ToString("yyyyMM");
            string   fileDir = Path.Combine(baseDir, subDir);

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

            string attachmentId    = System.Guid.NewGuid().ToString("D");
            string currentFileName = attachmentId + Path.GetExtension(originalFilePath);
            string currentFilePath = Path.Combine(fileDir, currentFileName);

            postedFile.SaveAs(currentFilePath);

            SysAttachment item = new SysAttachment();

            item.AttachmentId    = attachmentId;
            item.CurrentFileName = currentFileName;
            item.CurrentFileDir  = subDir;
            item.FileSize        = postedFile.ContentLength;
            // postedFile.
            item.OriginalFileName = Path.GetFileName(originalFilePath);
            item.UploadTime       = dt_now;
            item.UploadUser       = curr_user.UserId;
            item.ContentType      = postedFile.ContentType;
            item.PathId           = site_entity.CurrentUploadPathId;
            item.FileExtension    = Path.GetExtension(originalFilePath);

            SysBatchUpload batch_entity = new SysBatchUpload(batch_id, attachmentId);

            AttachmentDataAccess.InsertAttachment(item, batch_entity);

            return(item);
        }
Esempio n. 29
0
 public static void UploadFile(HttpPostedFile file, string originalName, string newName, string rootPath, out string filePath)
 {
     filePath = string.Empty;
     string path = GetUploadRootPath(rootPath);
     string tempPath = Path.Combine(path + @"Temp\", newName);
     AutoCreateUploadPath(path);
     file.SaveAs(Path.Combine(path + @"Temp\", newName));
     filePath = tempPath;
 }
Esempio n. 30
0
        private void UploadImage()
        {
            System.Drawing.Image image  = null;
            System.Drawing.Image image2 = null;
            Bitmap   bitmap             = null;
            Graphics graphics           = null;

            System.IO.MemoryStream memoryStream = null;
            try
            {
                System.Web.HttpPostedFile httpPostedFile = base.Request.Files["Filedata"];
                string str  = System.DateTime.Now.ToString("yyyyMMddHHmmss_ffff", System.Globalization.DateTimeFormatInfo.InvariantInfo);
                string str2 = Hidistro.Membership.Context.HiContext.Current.GetSkinPath() + "/UploadImage/" + this.slsbannerposition.Value + "/";
                string text = str + System.IO.Path.GetExtension(httpPostedFile.FileName);
                httpPostedFile.SaveAs(Globals.MapPath(str2 + text));
                base.Response.StatusCode = 200;
                base.Response.Write(string.Concat(new string[]
                {
                    Globals.ApplicationPath,
                    Hidistro.Membership.Context.HiContext.Current.GetSkinPath(),
                    "/UploadImage/",
                    this.slsbannerposition.Value,
                    "/",
                    text
                }));
            }
            catch (System.Exception)
            {
                base.Response.StatusCode = 500;
                base.Response.Write("服务器错误");
                base.Response.End();
            }
            finally
            {
                if (bitmap != null)
                {
                    bitmap.Dispose();
                }
                if (graphics != null)
                {
                    graphics.Dispose();
                }
                if (image2 != null)
                {
                    image2.Dispose();
                }
                if (image != null)
                {
                    image.Dispose();
                }
                if (memoryStream != null)
                {
                    memoryStream.Close();
                }
                base.Response.End();
            }
        }
Esempio n. 31
0
        /// <summary>
        /// 裁剪图片
        /// </summary>
        /// <param name="PostedFile">HttpPostedFile控件</param>
        /// <param name="SaveFolder">保存路径【sys.config配置路径】</param>
        /// <param name="oImgWidth">图片宽度</param>
        /// <param name="oImgHeight">图片高度</param>
        /// <param name="cMode">剪切类型</param>
        /// <returns>返回上传信息</returns>
        public ResponseMessage FileCutSaveAs(System.Web.HttpPostedFile PostedFile, string SaveFolder, int oImgWidth, int oImgHeight, CutMode cMode)
        {
            ResponseMessage rm = new ResponseMessage();

            try
            {
                //获取上传文件的扩展名
                string sEx = System.IO.Path.GetExtension(PostedFile.FileName);
                if (!CheckValidExt(SetAllowFormat, sEx))
                {
                    TryError(rm, 2);
                    return(rm);
                }

                //获取上传文件的大小
                double PostFileSize = PostedFile.ContentLength / 1024.0 / 1024.0;

                if (PostFileSize > SetAllowSize)
                {
                    TryError(rm, 3);
                    return(rm);  //超过文件上传大小
                }
                if (!System.IO.Directory.Exists(SaveFolder))
                {
                    System.IO.Directory.CreateDirectory(SaveFolder);
                }
                //重命名名称
                string NewfileName = 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("000");
                string fName       = "s" + NewfileName + sEx;
                string fullPath    = Path.Combine(SaveFolder, fName);
                PostedFile.SaveAs(fullPath);

                //重命名名称
                string sNewfileName = 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("000");
                string sFName       = sNewfileName + sEx;
                rm.IsError  = false;
                rm.FileName = sFName;
                string sFullPath = Path.Combine(SaveFolder, sFName);
                rm.filePath = sFullPath;
                rm.WebPath  = "/" + sFullPath.Replace(HttpContext.Current.Server.MapPath("~/"), "").Replace("\\", "/");
                CreateSmallPhoto(fullPath, oImgWidth, oImgHeight, sFullPath, SetPicWater, SetWordWater, cMode);
                if (File.Exists(fullPath))
                {
                    File.Delete(fullPath);
                }
                //压缩
                if (PostFileSize > 100)
                {
                    CompressPhoto(sFullPath, 100);
                }
            }
            catch (Exception ex)
            {
                TryError(rm, ex.Message);
            }
            return(rm);
        }
Esempio n. 32
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);
            }
        }
Esempio n. 33
0
        protected void Page_Load(object sender, System.EventArgs e)
        {
            if (base.Request.QueryString["delimg"] != null)
            {
                string path = base.Server.HtmlEncode(base.Request.QueryString["delimg"]);
                path = base.Server.MapPath(path);
                if (System.IO.File.Exists(path))
                {
                    System.IO.File.Delete(path);
                }
                base.Response.Write("0");
                base.Response.End();
            }
            int    num  = int.Parse(base.Request.QueryString["imgurl"]);
            string text = base.Request.QueryString["oldurl"].ToString();

            try
            {
                if (num < 1)
                {
                    System.Web.HttpPostedFile httpPostedFile = base.Request.Files["Filedata"];
                    string str   = System.DateTime.Now.ToString("yyyyMMddHHmmss_ffff", System.Globalization.DateTimeFormatInfo.InvariantInfo);
                    string text2 = "/Storage/master/topic/";
                    if (!System.IO.Directory.Exists(base.Server.MapPath(text2)))
                    {
                        System.IO.Directory.CreateDirectory(base.Server.MapPath(text2));
                    }
                    string text3 = str + System.IO.Path.GetExtension(httpPostedFile.FileName);
                    httpPostedFile.SaveAs(Globals.MapPath(text2 + text3));
                    if (!string.IsNullOrEmpty(text))
                    {
                        string path2 = base.Server.MapPath(text);
                        if (System.IO.File.Exists(path2))
                        {
                            System.IO.File.Delete(path2);
                        }
                    }
                    base.Response.StatusCode = 200;
                    base.Response.Write(str + "|/Storage/master/topic/" + text3);
                }
                else
                {
                    base.Response.Write("0");
                }
            }
            catch (System.Exception)
            {
                base.Response.StatusCode = 500;
                base.Response.Write("服务器错误");
                base.Response.End();
            }
            finally
            {
                base.Response.End();
            }
        }
Esempio n. 34
0
 private void UploadImage()
 {
     try
     {
         System.Web.HttpPostedFile httpPostedFile = System.Web.HttpContext.Current.Request.Files["Filedata"];
         string str  = System.DateTime.Now.ToString("yyyyMMddHHmmss_ffff", System.Globalization.DateTimeFormatInfo.InvariantInfo);
         string text = System.Web.HttpContext.Current.Request["uploadpath"];
         string str2 = str + System.IO.Path.GetExtension(httpPostedFile.FileName);
         if (string.IsNullOrEmpty(text))
         {
             ClientType clientType = ClientType.VShop;
             string     text2      = System.Web.HttpContext.Current.Request["clientType"];
             if (!string.IsNullOrWhiteSpace(text2))
             {
                 clientType = (ClientType)int.Parse(text2);
             }
             if (clientType == ClientType.VShop)
             {
                 text = HiContext.Current.GetVshopSkinPath(null) + "/images/ad/";
             }
             else
             {
                 if (clientType == ClientType.WAP)
                 {
                     text = HiContext.Current.GetWapshopSkinPath(null) + "/images/ad/";
                 }
                 else
                 {
                     if (clientType == ClientType.AliOH)
                     {
                         text = HiContext.Current.GetAliOHshopSkinPath(null) + "/images/ad/";
                     }
                 }
             }
             str2 = "imgCustomBg" + System.IO.Path.GetExtension(httpPostedFile.FileName);
             string[] files = System.IO.Directory.GetFiles(Globals.MapPath(text), "imgCustomBg.*");
             string[] array = files;
             for (int i = 0; i < array.Length; i++)
             {
                 string path = array[i];
                 System.IO.File.Delete(path);
             }
         }
         if (!System.IO.Directory.Exists(Globals.MapPath(text)))
         {
             System.IO.Directory.CreateDirectory(Globals.MapPath(text));
         }
         httpPostedFile.SaveAs(Globals.MapPath(text + str2));
         System.Web.HttpContext.Current.Response.Write(text + str2);
     }
     catch (System.Exception ex)
     {
         System.Web.HttpContext.Current.Response.Write("服务器错误" + ex.Message);
         System.Web.HttpContext.Current.Response.End();
     }
 }
Esempio n. 35
0
 public static void SaveFile(HttpPostedFile file, string format, object arg0, object arg1, Dictionary<string, string> credentials)
 {
     using (Impersonate i = new Impersonate(credentials["user"], credentials["pass"], credentials["domain"]))
     {
         if (i.isImpersonated())
         {
             file.SaveAs(string.Format(format, arg0, arg1));
         }
     }
 }
Esempio n. 36
0
 public void SavePicture(Product product, HttpPostedFile pictureFile)
 {
     Picture picture = new Picture()
     {
         Name = new Guid().ToString() + pictureFile.FileName.ToString(),
         ProductId = product.ProductId
     };
     product.Pictures.Add(picture);
     pictureFile.SaveAs("~/Images/" + picture.Name);
 }
Esempio n. 37
0
 public static string UploadCategoryImage(HttpPostedFile postedFile)
 {
     if (!CheckPostedFile(postedFile))
     {
         return string.Empty;
     }
     string str = "UploadedFile/Categories/" + GenerateFilename(Path.GetExtension(postedFile.FileName));
     postedFile.SaveAs(HttpContext.Current.Request.PhysicalApplicationPath+(Globals.ApplicationPath + str));
     return str;
 }
 public static string SaveUploadFile(System.Web.HttpPostedFile file, string storePath, string ext)
 {
     if (file != null)
     {
         string fileName = System.Guid.NewGuid().ToString() + ext;
         file.SaveAs(storePath + "\\" + fileName);
         return(fileName);
     }
     return(null);
 }
Esempio n. 39
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);
        }
Esempio n. 40
0
        protected void btnSaveImageData_Click(object sender, System.EventArgs e)
        {
            string str       = this.RePlaceImg.Value;
            int    photoId   = System.Convert.ToInt32(this.RePlaceId.Value);
            string photoPath = GalleryHelper.GetPhotoPath(photoId);
            string str2      = photoPath.Substring(photoPath.LastIndexOf("."));
            string extension = string.Empty;
            string str3      = string.Empty;

            try
            {
                System.Web.HttpPostedFile postedFile = base.Request.Files[0];
                extension = System.IO.Path.GetExtension(postedFile.FileName);
                if (str2 != extension)
                {
                    this.ShowMsg("上传图片类型与原文件类型不一致!", false);
                }
                else
                {
                    string str4 = Globals.GetStoragePath() + "/gallery";
                    str3 = photoPath.Substring(photoPath.LastIndexOf("/") + 1);
                    string str5                  = str.Substring(str.LastIndexOf("/") - 6, 6);
                    string virtualPath           = str4 + "/" + str5 + "/";
                    int    contentLength         = postedFile.ContentLength;
                    string path                  = base.Request.MapPath(virtualPath);
                    string text                  = str5 + "/" + str3;
                    System.IO.DirectoryInfo info = new System.IO.DirectoryInfo(path);
                    if (!info.Exists)
                    {
                        info.Create();
                    }
                    if (!ResourcesHelper.CheckPostedFile(postedFile))
                    {
                        this.ShowMsg("文件上传的类型不正确!", false);
                    }
                    else
                    {
                        if (contentLength >= 2048000)
                        {
                            this.ShowMsg("图片文件已超过网站限制大小!", false);
                        }
                        else
                        {
                            postedFile.SaveAs(base.Request.MapPath(virtualPath + str3));
                            GalleryHelper.ReplacePhoto(photoId, contentLength);
                            this.CloseWindow();
                        }
                    }
                }
            }
            catch
            {
                this.ShowMsg("替换文件错误!", false);
            }
        }
        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 }));
            }
        }
Esempio n. 42
0
        private void btnSaveImageFtp_Click(object sender, System.EventArgs e)
        {
            string str        = Globals.GetStoragePath() + "/gallery";
            int    categoryId = System.Convert.ToInt32(this.dropImageFtp.SelectedItem.Value);
            int    num2       = 0;
            int    num3       = 0;

            new System.Text.StringBuilder();
            System.Web.HttpFileCollection files = base.Request.Files;
            for (int i = 0; i < files.Count; i++)
            {
                System.Web.HttpPostedFile postedFile = files[i];
                if (postedFile.ContentLength > 0)
                {
                    num2++;
                    try
                    {
                        string str2                  = System.Guid.NewGuid().ToString("N", System.Globalization.CultureInfo.InvariantCulture) + System.IO.Path.GetExtension(postedFile.FileName);
                        string str3                  = postedFile.FileName.Substring(postedFile.FileName.LastIndexOf("\\") + 1);
                        string photoName             = str3.Substring(0, str3.LastIndexOf("."));
                        string str4                  = System.DateTime.Now.ToString("yyyyMM").Substring(0, 6);
                        string virtualPath           = str + "/" + str4 + "/";
                        int    contentLength         = postedFile.ContentLength;
                        string path                  = base.Request.MapPath(virtualPath);
                        string photoPath             = "/Storage/master/gallery/" + str4 + "/" + str2;
                        System.IO.DirectoryInfo info = new System.IO.DirectoryInfo(path);
                        if (ResourcesHelper.CheckPostedFile(postedFile))
                        {
                            if (!info.Exists)
                            {
                                info.Create();
                            }
                            postedFile.SaveAs(base.Request.MapPath(virtualPath + str2));
                            if (GalleryHelper.AddPhote(categoryId, photoName, photoPath, contentLength))
                            {
                                num3++;
                            }
                        }
                    }
                    catch
                    {
                    }
                }
            }
            if (num2 == 0)
            {
                this.ShowMsg("至少需要选择一个图片文件!", false);
            }
            else
            {
                this.ShowMsg("成功上传了" + num3.ToString() + "个文件!", true);
            }
        }
        public List <string> UploadFiles()
        {
            try
            {
                int           iUploadedCnt = 0;
                List <string> ImagePath    = new List <string>();

                // DEFINE THE PATH WHERE WE WANT TO SAVE THE FILES.
                Random r = new Random();

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

                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)
                    {
                        var addedName = r.Next(10000, 10000000).ToString();

                        // CHECK IF THE SELECTED FILE(S) ALREADY EXISTS IN FOLDER. (AVOID DUPLICATE)
                        if (!File.Exists(sPath + addedName + Path.GetFileName(hpf.FileName)))
                        {
                            // SAVE THE FILES IN THE FOLDER.
                            hpf.SaveAs(sPath + addedName + Path.GetFileName(hpf.FileName));
                            iUploadedCnt = iUploadedCnt + 1;
                            ImagePath.Add(VirtualUrl("Album/" + addedName + Path.GetFileName(hpf.FileName)));
                        }
                    }
                }

                // RETURN A MESSAGE (OPTIONAL).
                if (iUploadedCnt > 0)
                {
                    return(ImagePath);
                }
                else
                {
                    ImagePath.Clear();
                    ImagePath.Add("Upload Failed");
                    return(ImagePath);
                }
            }

            catch (HttpResponseException error)
            {
                throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, String.Format("Server error. Try again later. \n Server errors: {0}", error.Message)));
            }
        }
Esempio n. 44
0
        public ActionResult Create(string id, HttpPostedFile file)
        {
            var blogPost = RavenSession.Load<BlogPost>(id);

              var photo = new Photo { Path = "/public/" + Guid.NewGuid() };
              file.SaveAs(Server.MapPath(photo.Path));
              blogPost.Photos.Add(photo);

              RavenSession.SaveChanges();

              return RedirectToRoute(new { controller = "Blog", action = "Edit", id = id });
        }
 private void SaveFile(System.Web.HttpPostedFile file, string destination, string filename, out string msg)
 {
     try
     {
         file.SaveAs(destination + "/" + filename);
         msg = "";
     }
     catch (Exception ex)
     {
         msg = ex.Message + "/n" + ex.StackTrace;
     }
 }
        private string GetImageUrl(HttpPostedFile image)
        {
            string fileName = image.FileName + DateTime.Now.Ticks;
            string imagePath = HttpContext.Current.Server.MapPath("~/App_Data/") + fileName;
            image.SaveAs(imagePath);

            Entry imageEntry = DropboxUtilities.UploadImage(imagePath, dropbox, "New_Folder");

            DropboxLink imageLink = dropbox.GetMediaLinkAsync(imageEntry.Path).Result;

            File.Delete(imagePath);
            return imageLink.Url;
        }
Esempio n. 47
0
 public static string UpOrderFile(string username, HttpPostedFile file)
 {
     int lIndex = file.FileName.LastIndexOf('.');
     string lfilename = file.FileName.Substring(lIndex, file.FileName.Length - lIndex);
     string lGuidString = Guid.NewGuid().ToString();
     string lfilepath = RootOrder + username + "/" + lGuidString + lfilename;
     if (!System.IO.File.Exists(RootOrder + username + "/"))
     {
         System.IO.Directory.CreateDirectory(RootOrder + username + "/");
     }
     file.SaveAs(lfilepath);
     return lGuidString + lfilename;
 }
Esempio n. 48
0
 public static string Save(HttpServerUtility server, HttpPostedFile postedFile, string folder, string name = null)
 {
     if (postedFile == null) throw new ArgumentNullException("postedFile");
     if (folder == null) throw new ArgumentNullException("folder");
     if (name == null)
     {
         name = Path.GetRandomFileName();
         name = Path.ChangeExtension(name, "xlsx");
     }
     var fullPath = Path.Combine(server.MapPath(folder), name);
     postedFile.SaveAs(fullPath);
     return fullPath;
 }
 public void SaveResourceFile(string resourceToken, HttpPostedFile postedFile)
 {
     var extension = System.IO.Path.GetExtension(postedFile.FileName);
     var fileName = BusinessLayerParameters.UserDocumentFolderPrefix + Guid.NewGuid().ToString() + extension;
     var filePath = HttpContext.Current.Server.MapPath(fileName);
     postedFile.SaveAs(filePath);
     var resource = db.ResourcesReferences.FirstOrDefault(s => s.TokenValue == resourceToken);
     if (resource != null)
     {
         resource.FileExtension = extension;
         resource.ResourceUrl = fileName;
         db.SaveChanges();
     }
 }
Esempio n. 50
0
        private void process( HttpPostedFile file )
        {
            string path = this.Server.MapPath(UPLOAD_DIR) + Path.GetFileName(file.FileName);
            file.SaveAs( path );

            Playlist playlist = new Playlist(Regex.Replace(Path.GetFileName(file.FileName), @"\.doc", String.Empty));
            IList<Einsatz> einsaetze = FileUpload_Service.getEinsaetze(path, playlist);
            playlist.IsClosed = true;
            playlist.Sendetermin = this.dateTimeTryParse(file.FileName);
            FileUpload_Service.persist(playlist, einsaetze);

            this.lblMessage.ForeColor = Color.Green;
            lblMessage.Text += String.Format("'{0}' uploaded.", file.FileName);
        }
Esempio n. 51
0
 /// <summary>
 /// 上传文件
 /// </summary>
 /// <param name="postedFile">上传的文件</param>
 /// <param name="saveAsFullName">文件保存的完整路径</param>
 /// <param name="isReplace">如果有同名文件存在,是否覆盖</param>
 /// <returns>成功返回true,否则返回false</returns>
 public bool UploadFile(HttpPostedFile postedFile, string saveAsFullName, bool isReplace)
 {
     try
     {
         if (!isReplace && IsFileExists(saveAsFullName))
             return false;
         postedFile.SaveAs(saveAsFullName);
         return true;
     }
     catch (Exception ex)
     {
         throw ex;
     }
 }
Esempio n. 52
0
        protected void Button_Prueba_Click_k(HttpPostedFile archivo)
        {
            file = archivo;
            int fileSizeInBytes = file.ContentLength;
            string fileName = Request.Headers["X-File-Name"];
            string fileExtension = "";

            if (!string.IsNullOrEmpty(fileName))
                fileExtension = Path.GetExtension(fileName);

            // IMPORTANT! Make sure to validate uploaded file contents, size, etc. to prevent scripts being uploaded into your web app directory
            string savedFileName = Path.Combine(@"C:\Temp\", Guid.NewGuid().ToString() + fileExtension);
            file.SaveAs(savedFileName);
        }
        public static bool SaveDescriptionImage(HttpPostedFile OriginalFile)
        {
            string FileSuffix = Path.GetExtension(OriginalFile.FileName).Substring(1);
            bool ProcessResult = false;

            string FileName = GetDescriptionImageName(FileSuffix);

            if (config.AllowedFormat.ToLower().Contains(FileSuffix.ToLower()) && config.MaxSize * 1024 >= OriginalFile.ContentLength)
            {
                OriginalFile.SaveAs(config.PathRoot + FileName);
                ProcessResult = true;
            }

            return ProcessResult;
        }
Esempio n. 54
0
        public static string UpLoadFile(long companyId, long partId, int typeId, HttpPostedFile file)
        {
            string filePath = string.Empty;

            if (string.IsNullOrEmpty(file.FileName))
            {
                return file.FileName;
            }

            string filename = Path.GetFileName(file.FileName);
            string fileFormat = Path.GetExtension(file.FileName).Substring(1);

            if (!CheckFileType(fileFormat))
            {
                return filePath;
            }

            string folderPath = string.Empty;

            string DateFolderName = DateTime.Now.ToString("yy-MM-dd");
            string folderFmt = "{0}\\{1}\\{2}\\{3}\\{4}";//"files\\" + TabName + "\\" + DateFolderName;
            folderPath = string.Format(folderFmt, CASEROOTFOLDER, companyId, partId, typeId, DateFolderName);
            string physicalFolderPath = HttpContext.Current.Server.MapPath("/") + folderPath;

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

            if (!Directory.Exists(physicalFolderPath))
            {
                return string.Empty;
            }

            string fileNewName = filename;

            string SFolderFullPath = physicalFolderPath + "\\" + fileNewName;

            if (File.Exists(SFolderFullPath))
            {
                fileNewName = Path.GetFileNameWithoutExtension(file.FileName) + "(" + (new Random().Next(10, 99)) + ")." + fileFormat;
                SFolderFullPath = physicalFolderPath + "\\" + fileNewName;
            }

            file.SaveAs(SFolderFullPath);

            return ("\\" + folderPath + "\\" + fileNewName).Replace("\\", "/");
        }
Esempio n. 55
0
        //, int s_fileWidth, int s_fileHeight, string destinationFileName)
        public void Upload(HttpPostedFile myFile, string destinationPath)
        {
            if (myFile != null)
            {
                string fileName = myFile.FileName;
                string fileExtenstion = FileProcessor.GetFileExtension(fileName);

                if (myFile.ContentLength > 0 && myFile.ContentLength < 10 * 1024 * 1024)
                {
                    if (fileExtenstion == ".jpg" || fileExtenstion == ".jepg" || fileExtenstion == ".png" ||
                        fileExtenstion == ".gif")
                    {
                        //~/Content/Assets/Images/
                        //string path = Path.Combine(HttpContext.Current.Server.MapPath(destinationPath), Path.GetFileName(myFile.FileName));

                        //string picPath = Path.Combine(destinationPath, myFile.FileName);

                        ////string extension = FileProcessor.GetFileExtension(file.FileName);

                        //string purePath = HttpContext.Current.Server.MapPath(destinationPath);

                        myFile.SaveAs(destinationPath);

                        //Image img = Image.FromFile(path);

                        //string newFileName = user.UserProfile.FirstName + "_" + user.UserProfile.LastName +
                        //                     fileExtenstion;

                        //if (img.Width > s_fileWidth || img.Height > s_fileHeight)
                        //{
                        //    //resize image
                        //    //

                        //    ImageProcessor.SaveResizedImage(purePath, fileName, destinationFileName, s_fileWidth, s_fileHeight);
                        //}

                        //if (img.Width > l_fileWidth || img.Height > l_fileHeight)
                        //{
                        //    //resize image
                        //    //

                        //    ImageProcessor.SaveResizedImage(purePath, fileName, destinationFileName, l_fileWidth, l_fileHeight);
                        //}
                    }

                }
            }
        }
        public static bool SaveNewsImage(int NewsID, HttpPostedFile OriginalFile, out string ImageFileName)
        {
            string FileSuffix = Path.GetExtension(OriginalFile.FileName).Substring(1);
            bool ProcessResult = false;

            string FileName = String.Format(Config.Rule, NewsID, Guid.NewGuid(), FileSuffix);

            if (Config.AllowedFormat.ToLower().Contains(FileSuffix.ToLower()) && Config.MaxSize * 1024 >= OriginalFile.ContentLength)
            {
                OriginalFile.SaveAs(Config.PathRoot + FileName);
                ProcessResult = true;
            }

            ImageFileName = FileName;
            return ProcessResult;
        }
		/// <summary>
		/// Store the file entity body and its original name
		/// </summary>
		/// <param name="file"></param>
		public static void StoreUploadedFile(HttpPostedFile file)
		{
			if (HttpContextNull())
			{
				return;
			}

			string fileId = Guid.NewGuid().ToString("N");
			var dataPath = HttpContext.Current.Server.MapPath(appDataPath);

			file.SaveAs(Path.Combine(Path.Combine(dataPath, storagePath),fileId));
			File.WriteAllText(
				Path.Combine(dataPath, fileId + configExtension),
				StripFullName(file.FileName),
				System.Text.Encoding.UTF8);
		}
Esempio n. 58
0
		public static void UploadFile(ImageUploader uploadControl, HttpPostedFile file, string originalName, string newName, out string filePath)
		{
            filePath = string.Empty;

			string path = GetUploadRootPath("ImageUploadRootPath");
            string tempPath = Path.Combine(path + @"Temp\", newName);
			AutoCreateUploadPath(path);

			var beforeArgs = new UploadEventArgs(originalName);
			uploadControl.OnBeforeUploadFile(beforeArgs);
			file.SaveAs(Path.Combine(path + @"Temp\", newName));
			var afterArgs = new UploadEventArgs(newName);
			uploadControl.OnAfterUploadFile(afterArgs);

            filePath = tempPath;
		}
Esempio n. 59
-1
        public ActionResult AddImage(HttpPostedFile uploadFile, int eventID)
        {
            string[] all = Request.Files.AllKeys;

            foreach (string file in Request.Files.AllKeys)
            {
                HttpPostedFileBase hpf = Request.Files[file];
                if (hpf.ContentLength == 0)
                    continue;
                else
                {
                    var fileName = DateTime.Now.Ticks + Path.GetFileName(hpf.FileName);
                    var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory + "Images/uploads/", fileName);
                    uploadFile.SaveAs(path);
                }
            }

            ViewData["UploadSucceed"] = "Image upload succeded";
            return RedirectToAction("ShowImages", new { eventID = eventID });

            //if (uploadFile.ContentLength > 0)
            //{
            //    var fileName = DateTime.Now.Ticks + Path.GetFileName(uploadFile.FileName);
            //    var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory + "Images/uploads/", fileName);
            //    uploadFile.SaveAs(path);
            //    ViewData["UploadSucceed"] = "Image upload succeded";
            //    return RedirectToAction("ShowImages", new { eventID = eventID });
            //}
            //else
            //{
            //    ViewBag.UploadError = "";
            //    return View();
            //}
        }
Esempio n. 60
-11
 public static string Up(HttpPostedFile file)
 {
     string lfilename = file.FileName;
     string lfilepath = Root + lfilename;
     file.SaveAs(lfilepath);
     return lfilepath;
 }