当前位置: 首页>>代码示例>>C#>>正文


C# HttpPostedFile.SaveAs方法代码示例

本文整理汇总了C#中System.Web.HttpPostedFile.SaveAs方法的典型用法代码示例。如果您正苦于以下问题:C# HttpPostedFile.SaveAs方法的具体用法?C# HttpPostedFile.SaveAs怎么用?C# HttpPostedFile.SaveAs使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在System.Web.HttpPostedFile的用法示例。


在下文中一共展示了HttpPostedFile.SaveAs方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: FileSaveAs

        /// <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 = "上传过程中发生意外错误!" };
            }
        }
开发者ID:NickQi,项目名称:TianheDemo,代码行数:41,代码来源:AjaxImport.cs

示例2: AddImage

        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();
            //}
        }
开发者ID:uczenn,项目名称:Blog,代码行数:34,代码来源:ImageController.cs

示例3: SaveAs

        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 );
        }
开发者ID:powerumc,项目名称:AspNet-Blog,代码行数:26,代码来源:RepositoryAccess.cs

示例4: uploadFileControl

 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;
     }
 }
开发者ID:bookxiao,项目名称:orisoft,代码行数:35,代码来源:FileUpLoad.cs

示例5: UploadFile

        /// <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;
            }
        }
开发者ID:yftiger1981,项目名称:WlnPsyWeb,代码行数:35,代码来源:ExcelHelper.cs

示例6: SaveAs

 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);
 }
开发者ID:huaminglee,项目名称:myyyyshop,代码行数:7,代码来源:ProductSkuImgHandler.cs

示例7: SavePhoto

 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;
 }
开发者ID:pasha369,项目名称:RestaurantManagementSystem,代码行数:7,代码来源:ImageController.cs

示例8: SaveImageToCustomPath

        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;
        }
开发者ID:texPvtLtd,项目名称:2b728152-47df-422c-ae17-24aa1e963ffe,代码行数:25,代码来源:FileOperations.cs

示例9: fileSaveAs

		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;
		}
开发者ID:scutsky,项目名称:iyuewan,代码行数:59,代码来源:UpLoad.cs

示例10: HandleFile

 public UploadedFile HandleFile(HttpPostedFile postedFile)
 {
     var uploadedFile = new UploadedFile {Name = postedFile.FileName};
     uploadedFile.TempFilePathAbsolute.EnsureDirectoryExists();
     postedFile.SaveAs(uploadedFile.TempFilePathAbsolute);
     Files.Add(uploadedFile);
     return uploadedFile;
 }
开发者ID:teamaton,项目名称:speak-lib,代码行数:8,代码来源:UploadManager.cs

示例11: UploadFile

 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;
 }
开发者ID:jerryshi2007,项目名称:AK47Source,代码行数:9,代码来源:ImageUploadHelper.cs

示例12: SavePicture

 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);
 }
开发者ID:Matioz,项目名称:MyWebstore,代码行数:10,代码来源:PictureService.cs

示例13: UploadCategoryImage

 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;
 }
开发者ID:bookxiao,项目名称:orisoft,代码行数:10,代码来源:HiUploader.cs

示例14: SaveFile

 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));
         }
     }
 }
开发者ID:bkferareza,项目名称:DarthMaul,代码行数:10,代码来源:MiscHelper.cs

示例15: Create

        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 });
        }
开发者ID:haiku80,项目名称:raventest,代码行数:12,代码来源:PhotosController.cs


注:本文中的System.Web.HttpPostedFile.SaveAs方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。