• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

C# Web.HttpPostedFile类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



HttpPostedFile类属于System.Web命名空间,在下文中一共展示了HttpPostedFile类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C#代码示例。

示例1: ProcessFile

        public override void ProcessFile(HttpPostedFile file)
        {
            ManualResetEvent e = HttpContext.Current.Items["SyncUploadStorageAdapter"] as ManualResetEvent;

            try
            {
                UploadedFile item = UploadStorageService.CreateFile4Storage(file.ContentType);

                item.FileName = Path.GetFileName(file.FileName);
                item.ContentLength = file.ContentLength;
                item.InputStream = file.InputStream;

                if (!string.IsNullOrEmpty(HttpContext.Current.Request.Form["sectionId"]))
                {
                    Section section = Section.Load(new Guid(HttpContext.Current.Request.Form["sectionId"]));

                    if (section != null)
                        section.AddFile(item);
                }

                item.AcceptChanges();

                HttpContext.Current.Items["fileId"] = item.ID;
            }
            finally
            {
                if (e != null)
                {
                    Trace.WriteLine(string.Format("Signaling event for file in section {0}.", HttpContext.Current.Request.Form["sectionId"]));
                    e.Set();
                }
            }
        }
开发者ID:kohku,项目名称:codefactory,代码行数:33,代码来源:UploadStorageAdapter.cs


示例2: CheckUploadByTwoByte

        /// <summary>
        /// 根据文件的前2个字节进行判断文件类型  ---说明255216是jpg;7173是gif;6677是BMP,13780是PNG;7790是exe,8297是rar
        /// </summary>
        /// <param name="hpf"></param>
        /// <param name="code">文件的前2个字节转化出来的小数</param>
        /// <returns></returns>
        public bool CheckUploadByTwoByte(HttpPostedFile hpf, Int64 code)
        {
            System.IO.FileStream fs = new System.IO.FileStream(hpf.FileName, System.IO.FileMode.Open, System.IO.FileAccess.Read);
            System.IO.BinaryReader r = new System.IO.BinaryReader(fs);
            string fileclass = "";
            byte buffer;
            try
            {
                buffer = r.ReadByte();
                fileclass = buffer.ToString();
                buffer = r.ReadByte();
                fileclass += buffer.ToString();

            }
            catch
            {

            }
            r.Close();
            fs.Close();
            //
            //if (fileclass == code.ToString())
            //{
            //    return true;
            //}
            //else
            //{
            //    return false;
            //}
            return (fileclass == code.ToString());
        }
开发者ID:cj1324,项目名称:hanchenproject,代码行数:37,代码来源:UploadHelper.cs


示例3: GetFileBytes

 /// <summary>
 /// Gets the file bytes
 /// </summary>
 /// <param name="context">The context.</param>
 /// <param name="uploadedFile">The uploaded file.</param>
 /// <returns></returns>
 public virtual byte[] GetFileBytes( HttpContext context, HttpPostedFile uploadedFile )
 {
     // NOTE: GetFileBytes can get overridden by a child class (ImageUploader.ashx.cs for example)
     var bytes = new byte[uploadedFile.ContentLength];
     uploadedFile.InputStream.Read( bytes, 0, uploadedFile.ContentLength );
     return bytes;
 }
开发者ID:CentralAZ,项目名称:Rockit-CentralAZ,代码行数:13,代码来源:FileUploader.ashx.cs


示例4: AddFileToSession

        public void AddFileToSession(string controlId, string filename, HttpPostedFile fileUpload)
        {
            if (fileUpload == null)
            {
                throw new ArgumentNullException("fileUpload");
            }
            else if (controlId == String.Empty)
            {
                throw new ArgumentNullException("controlId");
            }

            HttpContext currentContext = null;
            if ((currentContext = GetCurrentContext()) != null)
            {
                var mode = currentContext.Session.Mode;
                if (mode != SessionStateMode.InProc) {
            #if NET4
                    throw new InvalidOperationException(Resources_NET4.SessionStateOutOfProcessNotSupported);
            #else
                    throw new InvalidOperationException(Resources.SessionStateOutOfProcessNotSupported);
            #endif
                }
                currentContext.Session.Add(GetFullID(controlId), fileUpload);
            }
        }
开发者ID:sumutcan,项目名称:WTWP-Ticket-Booking,代码行数:25,代码来源:PersistedStoreManager.cs


示例5: DescribePostedFile

        internal static string DescribePostedFile(HttpPostedFile file)
        {
            if (file.ContentLength == 0 && string.IsNullOrEmpty(file.FileName))
                return "[empty]";

            return string.Format("{0} ({1}, {2} bytes)", file.FileName, file.ContentType, file.ContentLength);
        }
开发者ID:nover,项目名称:RollbarSharp,代码行数:7,代码来源:RequestModelBuilder.cs


示例6: UnpackToFile

 /// <summary>
 ///     Unpacks to file.
 /// </summary>
 /// <param name="args">The arguments.</param>
 /// <param name="file">The file.</param>
 private static void UnpackToFile(UploadArgs args, HttpPostedFile file)
 {
     Assert.ArgumentNotNull(args, "args");
     Assert.ArgumentNotNull(file, "file");
     var filename = FileUtil.MapPath(TempFolder.GetFilename("temp.zip"));
     file.SaveAs(filename);
     using (var zipReader = new ZipReader(filename))
     {
         foreach (var zipEntry in zipReader.Entries)
         {
             var str = FileUtil.MakePath(args.Folder, zipEntry.Name, '\\');
             if (zipEntry.IsDirectory)
             {
                 Directory.CreateDirectory(str);
             }
             else
             {
                 if (!args.Overwrite)
                     str = FileUtil.GetUniqueFilename(str);
                 Directory.CreateDirectory(Path.GetDirectoryName(str));
                 lock (FileUtil.GetFileLock(str))
                     FileUtil.CreateFile(str, zipEntry.GetStream(), true);
             }
         }
     }
 }
开发者ID:raynjamin,项目名称:Sitecore-S3-Media,代码行数:31,代码来源:SaveImagesToS3.cs


示例7: SaveProductMainImage

        public static bool SaveProductMainImage(int ProductID, HttpPostedFile OriginalFile, out string[] FileNames)
        {
            string FileSuffix = Path.GetExtension(OriginalFile.FileName).Substring(1);
            bool ProcessResult = false;
            FileNames = GetMainImageName(ProductID, FileSuffix);
            if (!Directory.Exists(config.PathRoot)) Directory.CreateDirectory(config.PathRoot);

            if (config.AllowedFormat.ToLower().Contains(FileSuffix.ToLower()) && config.MaxSize * 1024 >= OriginalFile.ContentLength)
            {
                ImageHelper ih = new ImageHelper();

                ih.LoadImage(OriginalFile.InputStream);

                for (int i = 2; i >= 0; i--)
                {
                    if (config.ImageSets[i].Width > 0 && config.ImageSets[i].Height > 0)
                    {
                        ih.ScaleImageByFixSize(config.ImageSets[i].Width, config.ImageSets[i].Height, true);
                    }
                    ih.SaveImage(config.PathRoot + FileNames[i]);
                }

                ih.Dispose();
                //foreach (string FileName in FileNames)
                //{
                //    //缩小图片为设置尺寸注意图片尺寸与名称对应
                //    OriginalFile.SaveAs(config.PathRoot + FileName);
                //}

                ProcessResult = true;
            }

            return ProcessResult;
        }
开发者ID:ViniciusConsultor,项目名称:noname-netshop,代码行数:34,代码来源:MagicWorldImageRule.cs


示例8: 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


示例9: PostedFile

		public PostedFile(HttpPostedFile httpPostedFile)
		{
			_fileName = httpPostedFile.FileName;
			_stream = httpPostedFile.InputStream;
			_contentType = httpPostedFile.ContentType;
			_length = httpPostedFile.ContentLength;
		}
开发者ID:kendarorg,项目名称:Node.Cs.Old,代码行数:7,代码来源:PostedFile.cs


示例10: MemoryStreamSmall

        void MemoryStreamSmall(HttpPostedFile hpFile, string name, string type, int Width, int Height)
        {
            Image img = Image.FromStream(hpFile.InputStream);
            Bitmap bit = new Bitmap(img);

            if (bit.Width > Width || bit.Height > Height)
            {

                int desiredHeight = bit.Height;

                int desiredWidth = bit.Width;

                double heightRatio = (double)desiredHeight / desiredWidth;

                double widthRatio = (double)desiredWidth / desiredHeight;


                if (heightRatio > 1)
                {
                    Width = Convert.ToInt32(Height * widthRatio);
                }
                else
                {
                    Height = Convert.ToInt32(Width * heightRatio);
                }

                bit = new Bitmap(bit, Width, Height);//图片缩放
            }

            bit.Save(name.Substring(0, name.LastIndexOf('.')) + "A." + type, System.Drawing.Imaging.ImageFormat.Jpeg);
        }
开发者ID:BlueZore,项目名称:ImageGroupUpload,代码行数:31,代码来源:UploadHandler.ashx.cs


示例11: GenerateVersions

        //temp
        public bool GenerateVersions(HttpPostedFile file, string leafDirectoryName, string origFileName)
        {
            Dictionary<string, string> versions = new Dictionary<string, string>();
            //Define the version to generate
            versions.Add("_thumb", "width=100&height=100&crop=auto&format=jpg"); //Crop to square thumbnail
            versions.Add("_medium", "maxwidth=400&maxheight=400format=jpg"); //Fit inside 400x400 area, jpeg

            //Loop through each uploaded file
            foreach (string fileKey in HttpContext.Current.Request.Files.Keys)
            {
                if (file.ContentLength <= 0) continue; //Skip unused file controls.
                var uploadFolder = GetPhysicalPathForFile(file, leafDirectoryName);
                if (!Directory.Exists(uploadFolder)) Directory.CreateDirectory(uploadFolder);
                //Generate each version
                string[] spFiles = origFileName.Split('.');
                foreach (string suffix in versions.Keys)
                {
                    string appndFileName = spFiles[0] + suffix;
                    string fileName = Path.Combine(uploadFolder, appndFileName);
                    fileName = ImageBuilder.Current.Build(file, fileName, new ResizeSettings(versions[suffix]), false,
                                                          true);
                }

            }
            return true;
        }
开发者ID:reharik,项目名称:MethodFitness,代码行数:27,代码来源:IFileHandlerService.cs


示例12: 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


示例13: 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


示例14: SaveAspect

        public override ImagePreviewDTO SaveAspect(HttpPostedFile file)
        {
            ImagePreviewDTO previewDTO = base.SaveAspect(file);
            string Folder_60X60 = string.Format("{0}\\60X60", this.FolderServerPath);
            string Folder_120X120 = string.Format("{0}\\120X120", this.FolderServerPath);

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

            string fileName_60X60 = string.Format(Folder_60X60 + "\\{0}", previewDTO.FileName);
            string fileName_120X120 = string.Format(Folder_120X120 + "\\{0}", previewDTO.FileName);
            string orignalFilePath = string.Format(this.OrignalImageServerPath + "\\{0}", previewDTO.FileName);
            //自己需要使用的尺寸
            IWEHAVE.ERP.GAIA.WEBUtil.FileManage.MakeThumbnail(orignalFilePath, fileName_60X60, 60, 60, "AHW");
            IWEHAVE.ERP.GAIA.WEBUtil.FileManage.MakeThumbnail(orignalFilePath, fileName_120X120, 120, 120, "AHW");
            CompanyImagePreviewDTO companyPreviewDTO = new CompanyImagePreviewDTO(previewDTO);
            companyPreviewDTO.Image_60X60 = string.Format("{0}/60X60/{1}", this.FolderPath, previewDTO.FileName);
            companyPreviewDTO.Image_120X120 = string.Format("{0}/120X120/{1}", this.FolderPath, previewDTO.FileName);
            return companyPreviewDTO;
        }
开发者ID:AllanHao,项目名称:WebSystem,代码行数:26,代码来源:CompanyImageAspect.cs


示例15: CreateBllImage

 public static byte[] CreateBllImage(HttpPostedFile loadImage)
 {
     var image = new byte[loadImage.ContentLength];
     loadImage.InputStream.Read(image, 0, loadImage.ContentLength);
     loadImage.InputStream.Close();
     return image;
 }
开发者ID:kinderswan,项目名称:BriefList,代码行数:7,代码来源:Image.cs


示例16: UpLoadImage

        //上传图片方法
        private void UpLoadImage(HttpPostedFile file)
        {
            string fileExt = Path.GetExtension(file.FileName);
            if (fileExt != ".jpg" && fileExt != ".png")
            {
                return;
            }
            string newFileName = Common.CommonTools.GetStreamMD5(file.InputStream) + fileExt;//Guid.NewGuid().ToString() + fileExt;//创建新的文件名

            DateTime nowDate = DateTime.Now;
            string dir = string.Format("/{0}/{1}/", nowDate.Year, nowDate.Month);

            if (!Directory.Exists(dir))
            {
                Directory.CreateDirectory(Path.GetDirectoryName(HttpContext.Current.Request.MapPath(dir)));
            }
            file.SaveAs(HttpContext.Current.Request.MapPath(dir + newFileName));
            using (Image image = Image.FromStream(file.InputStream))
            {

                HttpContext.Current.Response.Write("success," + dir + newFileName + "," + image.Width + "," + image.Height);
                //var obj = new
                //{
                //    ReturnCode = "success",
                //    ImagePath = dir + newFileName,
                //    Width = image.Width,
                //    Height = image.Height
                //};
                //JavaScriptSerializer js = new JavaScriptSerializer();
                //HttpContext.Current.Response.Write(js.Serialize(obj));
            }
        }
开发者ID:fqncom,项目名称:tomcraporigami,代码行数:33,代码来源:UpLoadFile.ashx.cs


示例17: CreateFile

        public WikiFile CreateFile(string fileName, Guid listingVersionGuid, Guid vendorGuid, HttpPostedFile file, FileType fileType, List<UmbracoVersion> v, string dotNetVersion, bool mediumTrust)
        {
            // we have to convert to the uWiki UmbracoVersion :(

            List<UmbracoVersion> vers = new List<UmbracoVersion>();

            foreach (var ver in v)
            {
                vers.Add(UmbracoVersion.AvailableVersions()[ver.Version]);
            }

            //Create the Wiki File
            var uWikiFile = WikiFile.Create(fileName, listingVersionGuid, vendorGuid, file, GetFileTypeAsString(fileType), vers);
            //return the IMediaFile

            //Convert to Deli Media file
            var MediaFile = GetFileById(uWikiFile.Id);

            // If upload is package, extract the package XML manifest and check the version number + type [LK:[email protected]]
            if (fileType == FileType.package)
            {
                var minimumUmbracoVersion = GetMinimumUmbracoVersion(MediaFile);
                if (!string.IsNullOrWhiteSpace(minimumUmbracoVersion))
                {
                    MediaFile.Versions = new List<UmbracoVersion>() { new UmbracoVersion { Version = minimumUmbracoVersion } };
                }
            }

            MediaFile.DotNetVersion = dotNetVersion;
            SaveOrUpdate(MediaFile);
            return MediaFile;
        }
开发者ID:ClaytonWang,项目名称:OurUmbraco,代码行数:32,代码来源:MediaProvider.cs


示例18: 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


示例19: AddFile

 internal void AddFile(string key, HttpPostedFile file)
 {
     this.ThrowIfMaxHttpCollectionKeysExceeded();
     this._all = null;
     this._allKeys = null;
     base.BaseAdd(key, file);
 }
开发者ID:pritesh-mandowara-sp,项目名称:DecompliedDotNetLibraries,代码行数:7,代码来源:HttpFileCollection.cs


示例20: SaveGroup

 public void SaveGroup(Group group, HttpPostedFile file, List<long> selectedGroupTypeIDs)
 {
     if (group.Description.Length > 2000)
     {
         _view.ShowMessage("Your description is " + group.Description.Length.ToString() +
                           " characters long and can only be 2000 characters!");
     }
     else
     {
         group.AccountID = _webContext.CurrentUser.AccountID;
         group.PageName = group.PageName.Replace(" ", "-");
         if (group.GroupID == 0 && _groupRepository.CheckIfGroupPageNameExists(group.PageName))
         {
             _view.ShowMessage("The page name you specified is already in use!");
         }
         else
         {
             if (file.ContentLength > 0)
             {
                 List<Int64> fileIDs = _fileService.UploadPhotos(1, _webContext.CurrentUser.AccountID,
                                                                 _webContext.Files, 2);
                 //should only be one item uploaded!
                 if (fileIDs.Count == 1)
                     group.FileID = fileIDs[0];
             }
             group.GroupID = _groupService.SaveGroup(group);
             _groupToGroupTypeRepository.SaveGroupTypesForGroup(selectedGroupTypeIDs, group.GroupID);
             _redirector.GoToGroupsViewGroup(group.PageName);
         }
     }
 }
开发者ID:ngocpq,项目名称:MHX2,代码行数:31,代码来源:ManageGroupPresenter.cs



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# Web.HttpPostedFileBase类代码示例发布时间:2022-05-26
下一篇:
C# Web.HttpFileCollectionBase类代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap