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

C# Web.HttpPostedFileBase类代码示例

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

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



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

示例1: UploadFile

        public static FTPResultFile UploadFile(FtpModel model, HttpPostedFileBase file)
        {
            FTPResultFile result = null;
            try
            {
                string ftpfullpath = model.Server + model.Directory + file.FileName;
                FtpWebRequest ftp = (FtpWebRequest)FtpWebRequest.Create(ftpfullpath);
                ftp.Credentials = new NetworkCredential(model.Username, model.Password);

                ftp.KeepAlive = true;
                ftp.UseBinary = true;
                ftp.Method = WebRequestMethods.Ftp.UploadFile;

                Stream fs = file.InputStream;
                byte[] buffer = new byte[fs.Length];
                fs.Read(buffer, 0, buffer.Length);
                fs.Close();

                Stream ftpstream = ftp.GetRequestStream();
                ftpstream.Write(buffer, 0, buffer.Length);
                ftpstream.Close();

                result.IsSuccess = true;
                
            }
            catch (Exception ex)
            {
                result.Exception = ex;
                result.IsSuccess = false;
            }

            return result;

        }
开发者ID:yakintech,项目名称:YakinTech.FTP,代码行数:34,代码来源:FTPProvider.cs


示例2: IsWebFriendlyImage

        public static bool IsWebFriendlyImage(HttpPostedFileBase file)
        {
            //check for actual object
            if (file == null)
            {
                return false;
            }

            //check size - file must be less than 2MB and greater than 1KB
            if (file.ContentLength > 2 * 1024 * 1024 || file.ContentLength < 1024)
            {
                return false;
            }

            try
            {
                using (var img = Image.FromStream(file.InputStream))
                {
                    return ImageFormat.Jpeg.Equals(img.RawFormat) ||
                           ImageFormat.Png.Equals(img.RawFormat) ||
                           ImageFormat.Gif.Equals(img.RawFormat);
                }

            }

            catch
            {
                return false;
            }
        }
开发者ID:dankin-code,项目名称:Blog,代码行数:30,代码来源:ImageUploadValidator.cs


示例3: FileUpload

        public ActionResult FileUpload(HttpPostedFileBase file)
        {
            if (Request.Files.Count==0)
            {
                return Json(new { jsonrpc = 2.0, error = new { code = 102, message = "保存失败" }, id = "id" });
            }

            string extension = Path.GetExtension(file.FileName);
            string filePathName = Guid.NewGuid().ToString("N") + extension;

            if (!Directory.Exists(@"c:\temp"))
            {
                Directory.CreateDirectory(@"c:\temp");
            }

            filePathName = @"c:\temp\" + filePathName;
            file.SaveAs(filePathName);

            Stream stream = file.InputStream;

            //using (FileStream fs = stream)
            //{

            //}

            ResumablePutFile("magiccook", Guid.NewGuid().ToString("N"),stream);

            return Json(new { success = true });
        }
开发者ID:Jesn,项目名称:osharp,代码行数:29,代码来源:UploaderController.cs


示例4: updateImage

        public string updateImage(HttpPostedFileBase file, string objectName, string method)
        {
            if (file != null)
            {

                string filePath = "/Images/Members/" + objectName;

                string saveFileName = "/ProfilePicture" + ".png";// fileName;
                switch (method)
                {
                    case "HeadlineHeader":
                        filePath = "/Images/Headlines/" + objectName + "/";
                        var fileNameNoExtension = file.FileName;
                        fileNameNoExtension = fileNameNoExtension.Substring(0, fileNameNoExtension.IndexOf("."));
                        saveFileName = file.FileName.Replace(fileNameNoExtension, "header");

                        break;
                }
                string directoryPath = System.Web.HttpContext.Current.Server.MapPath(filePath);
                if (!Directory.Exists(directoryPath))
                {
                    Directory.CreateDirectory(directoryPath);
                }

                string path = filePath + saveFileName;
                file.SaveAs(System.Web.HttpContext.Current.Server.MapPath("~" + path));
                return path;
            }
            else return "";
        }
开发者ID:venoirEnterprises,项目名称:base,代码行数:30,代码来源:fileServices.cs


示例5: Create

        public ActionResult Create(Product product, HttpPostedFileBase image)
        {
            if (ModelState.IsValid)
            {
                if (image != null)
                {
                    product.ImageMimeType = image.ContentType;
                    product.ImageData = new byte[image.ContentLength];
                    image.InputStream.Read(product.ImageData, 0, image.ContentLength);
                }
                else
                {
                    byte[] imageByte = System.IO.File.ReadAllBytes(Server.MapPath("~/Images/defaultProduct.gif"));
                    product.ImageData = imageByte;
                    product.ImageMimeType = "image/gif";
                }

                // Date product was created
                product.UserId = WebSecurity.GetUserId(User.Identity.Name);
                product.DataCreated = DateTime.Now;

                db.Products.Add(product);
                db.SaveChanges();

                return RedirectToAction("Index");
            }
            return View(product);
        }
开发者ID:cristianomj,项目名称:yackimo,代码行数:28,代码来源:ProductController.cs


示例6: Create

        public ActionResult Create(Personnel personnel, HttpPostedFileBase file)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    //image upload
                    if (file == null || !isImageValid(file))
                    {
                        ModelState.AddModelError(string.Empty, string.Empty);
                    }
                    else
                    {
                        isActivePersonel(personnel);
                        db.Insert(personnel);

                        //Save Image File to Local
                        string imagePath = "~/Uploads/Images/" + "Image_" + personnel.ID + ".png";
                        saveImage(file, imagePath);

                        //Save Image Path to DB and Update Personnel
                        personnel.PhotoPath = imagePath;
                        db.Update(personnel);

                        return RedirectToAction("Index");
                    }
                }
                catch (Exception)
                {
                    throw;
                }
            }
            return View(personnel);
        }
开发者ID:panyhenzeta,项目名称:PersonelTakipSistemi,代码行数:34,代码来源:PersonnelController.cs


示例7: Create

        public ActionResult Create(Ruta art, HttpPostedFileBase file)
        {
            string fileName = "", path = "";
            // Verify that the user selected a file
            if (file != null && file.ContentLength > 0)
            {
                // extract only the fielname
                fileName = Path.GetFileName(file.FileName);
                // store the file inside ~/App_Data/uploads folder
                path = Path.Combine(Server.MapPath("~/Images/Uploads"), fileName);
                //string pathDef = path.Replace(@"\\", @"\");
                file.SaveAs(path);
            }

            try
            {
                fileName = "/Images/Uploads/" + fileName;
                ArticuloCEN cen = new ArticuloCEN();
                cen.New_(art.Descripcion, art.Precio, art.IdCategoria, fileName, art.Nombre);

                return RedirectToAction("PorCategoria", new { id=art.IdCategoria});
            }
            catch
            {
                return View();
            }
        }
开发者ID:chespii12,项目名称:DSM_Travelnook,代码行数:27,代码来源:ArticuloController.cs


示例8: Create

        public ActionResult Create([Bind(Include = "Id,BillTypeNumber,BillTypeName,BillNumber,ContractNumber,FirstParty,SecondParty,SignDate,DueDate,Amount,ContractObject,ContractAttachmentType,ContractAttachmentName,ContractAttachmentUrl,Remark")] Contract contract, HttpPostedFileBase file)
        {
            if (ModelState.IsValid)
            {

                //{if (file != null)
                //    contract.ContractAttachmentType = file.ContentType;//获取图片类型
                //   contract.ContractAttachment = new byte[file.ContentLength];//新建一个长度等于图片大小的二进制地址
                //   file.InputStream.Read(contract.ContractAttachment, 0, file.ContentLength);//将image读取到Logo中
                //}

                if (!HasFiles.HasFile(file))
                {
                    ModelState.AddModelError("", "文件不能为空!");
                    return View(contract);
                }

                string miniType = file.ContentType;
                Stream fileStream =file.InputStream;
                string path = AppDomain.CurrentDomain.BaseDirectory + "files\\";
                string filename = Path.GetFileName(file.FileName);
                 file.SaveAs(Path.Combine(path, filename));

                   contract.ContractAttachmentType = miniType;
                    contract.ContractAttachmentName = filename;
                    contract.ContractAttachmentUrl = Path.Combine(path, filename);

                db.Contracts.Add(contract);//存储到数据库
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(contract);
        }
开发者ID:Golry,项目名称:Bonsaii2,代码行数:34,代码来源:ContractController.cs


示例9: Create

        public ActionResult Create([Bind(Include="ID,TITLE,WRITER,WEBSITE,PUBLISHED_DATE,CONTENT,IMAGE_NAME,VIDEO_NAME")] PostItem postitem,
                                   HttpPostedFileBase imageFile, HttpPostedFileBase videoFile)
        {
            if (ModelState.IsValid)
            {
                if (imageFile != null)
                {
                    postitem.IMAGE_NAME = imageFile.FileName;
                }
                if (videoFile != null)
                {
                    postitem.VIDEO_NAME = videoFile.FileName;
                }
                db.Posts.Add(postitem);
                db.SaveChanges();

                // Checks whether the image / video file is not empty
                if (imageFile != null && imageFile.ContentLength > 0)
                {
                    string imageName = postitem.IMAGE_NAME;
                    string path = Server.MapPath("~/Uploads");
                    imageFile.SaveAs(Path.Combine(path, imageName));
                }
                if (videoFile != null && videoFile.ContentLength > 0)
                {
                    string videoName = postitem.VIDEO_NAME;
                    string path = Server.MapPath("~/Uploads");
                    videoFile.SaveAs(Path.Combine(path, videoName));
                }

                return RedirectToAction("Index");
            }

            return View(postitem);
        }
开发者ID:itays02,项目名称:ShauliProject,代码行数:35,代码来源:PostsController.cs


示例10: Create

        public ActionResult Create(CreateCourseScoViewModel form, HttpPostedFileBase file)
        {
            var filePackage = FileServices.Upload_Backup_and_then_ExtractZip(file, Server, AppConstants.ScoDirectory);
            if (!ModelState.IsValid  || filePackage == null) return View(form);

            var sco = new Sco
            {
                Title = filePackage.Name,
                Directory = filePackage.Directory
            };
            _context.Scos.Add(sco);
            _context.SaveChanges();


            //Add the sco to the new CourseSco and save
            var courseSco = new CourseSco
            {
                Title = sco.Title,
                CourseTemplateId = form.CourseId,
                CatalogueNumber = form.CatalogueNumber,
                RequiredScoId = form.RequiredScoId,
                ScoId = sco.Id
            };
            _context.CourseScos.Add(courseSco);
            _context.SaveChanges();
            return RedirectToAction("Index", new { id = form.CourseId });
        }
开发者ID:rswetnam,项目名称:GoodBoating,代码行数:27,代码来源:ManageCourseScosController.cs


示例11: UploadSingleFileToServer

        /// <summary>upload single file to file server</summary>
        /// <param name="fileVersionDTO">file version dto which contains information for file which is to be save</param>
        /// <param name="postedFile">Posted file which is to be save on file server</param>
        /// <returns>Success or failure of operation to save file on server wrapped in operation result</returns>
        public static OperationResult<bool> UploadSingleFileToServer(IFileVersionDTO fileVersionDTO, HttpPostedFileBase postedFile)
        {
            OperationResult<bool> result;
            try
            {
                if (fileVersionDTO != null && postedFile != null && postedFile.ContentLength > 0)
                {
                    if (Directory.Exists(fileVersionDTO.ServerPath))
                    {
                        var path = Path.Combine(
                            fileVersionDTO.ServerPath,
                            fileVersionDTO.ServerFileName);

                        postedFile.SaveAs(path);
                        result = OperationResult<bool>.CreateSuccessResult(true, "File Successfully Saved on file server.");
                    }
                    else
                    {
                        result = OperationResult<bool>.CreateFailureResult("Path doesn't exist.");
                    }
                }
                else
                {
                    result = OperationResult<bool>.CreateFailureResult("There is no file to save.");
                }
            }
            catch (Exception ex)
            {
                result = OperationResult<bool>.CreateErrorResult(ex.Message, ex.StackTrace);
            }

            return result;
        }
开发者ID:tmccord123,项目名称:TMCMaster1,代码行数:37,代码来源:FileUploadUtility.cs


示例12: UploadFile

        public async Task<string> UploadFile(string fileName, HttpPostedFileBase file)
        {
            // TODO: 
            // https://azure.microsoft.com/en-us/documentation/articles/storage-dotnet-how-to-use-blobs/#programmatically-access-blob-storage
            // - Add proper nuget
            // - Connect to storage
            // - create container
            // - upload blob
            // - return URL

            // Retrieve storage account from connection string.
            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(ConfigurationManager.AppSettings["StorageConnectionString"]);

            // Create the blob client.
            CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();

            // Retrieve a reference to a container.
            CloudBlobContainer container = blobClient.GetContainerReference(ContainerName);

            // Create the container if it doesn't already exist.
            container.CreateIfNotExists();

            // Retrieve reference to a blob named "myblob".
            CloudBlockBlob blockBlob = container.GetBlockBlobReference(fileName);

            await blockBlob.UploadFromStreamAsync(file.InputStream);

            return blockBlob.Uri.ToString();
        }
开发者ID:ptekla,项目名称:AzureConstructionsProgressTracker-AzureWorkshopFP,代码行数:29,代码来源:FilesStorageService.cs


示例13: UploadLogo

 public ActionResult UploadLogo(AddLogo logo, HttpPostedFileBase file)
 {
     RDN.Library.Classes.Team.TeamFactory.SaveLogoToDbForTeam(file, new Guid(), logo.TeamName);
     ViewBag.Saved = true;
     ApiCache.ClearCache();
     return View(logo);
 }
开发者ID:mukhtiarlander,项目名称:git_demo_torit,代码行数:7,代码来源:TeamController.cs


示例14: Upload

        public ActionResult Upload(HttpPostedFileBase file, string path)
        {
            try
            {
                var orig = path;
                if (file == null) throw new Exception("File not supplied.");
                if (!User.IsInRole("Files")) return Redirect(Url.Action<FilesController>(x => x.Browse(null)) + "?warning=Access Denied.");

                string root = ConfigurationManager.AppSettings["FilesRoot"];
                root = root.Trim().EndsWith(@"\") ? root = root.Substring(0, root.Length - 2) : root;

                if (!path.StartsWith("/")) path = "/" + path;

                path = string.Format(@"{0}{1}", ConfigurationManager.AppSettings["FilesRoot"], path.Replace("/", "\\"));

                var temp = path.EndsWith("\\") ? (path + file.FileName) : (path + "\\" + file.FileName);

                file.SaveAs(temp);
                return Redirect(Url.Action<FilesController>(x => x.Browse(orig)) + "?success=File Saved!");
            }
            catch (Exception ex)
            {
                return Redirect(Url.Action<FilesController>(x => x.Browse(null)) + "?error=" + Server.UrlEncode(ex.Message));
            }
        }
开发者ID:jslaybaugh,项目名称:rephidim-web,代码行数:25,代码来源:FilesController.cs


示例15: Index

        public ActionResult Index(HttpPostedFileBase uploadFile)
        {
            if (uploadFile.ContentLength > 0)
            {
                var streamReader = new StreamReader(uploadFile.InputStream);

                var gtinList = new List<string>();
                while (!streamReader.EndOfStream)
                {
                    gtinList.Add(streamReader.ReadLine());
                }

                var productsWithInfo = new List<string>();
                var productsWithAdvices = new List<string>();
                foreach (var gtin in gtinList)
                {
                    var result = _productApplicationService.FindProductByGtin(gtin, true);
                    if (!string.IsNullOrEmpty(result.ProductName))
                    {
                        productsWithInfo.Add(result.ProductName);
                    }
                    if (result.ProductAdvices.Count > 0
                        || result.Brand.BrandAdvices.Count > 0
                        || (result.Brand.Owner != null && result.Brand.Owner.CompanyAdvices.Count > 0)
                        || result.Ingredients.Any(x => x.IngredientAdvices.Count > 0))
                    {
                        productsWithAdvices.Add(result.ProductName);
                    }
                }
                ViewData["ProdWithInfo"] = productsWithInfo;
                ViewData["ProdWithAdvices"] = productsWithAdvices;
            }
            return View();
        }
开发者ID:consumentor,项目名称:Server,代码行数:34,代码来源:PerformanceTestController.cs


示例16: UploadImage

        public static UploadResult UploadImage(HttpPostedFileBase fileimage)
        {
            try
            {
                if (fileimage == null)
                {
                    return new UploadResult
                    {
                        IsSuccess = false,
                        FileName = "",
                        Result = "",
                        ImageThumbnail = ""
                    };
                }

                if (!ExtentionFile.CheckExtentionFileImage(fileimage.FileName.ToLower()))
                {
                    return new UploadResult
                    {
                        IsSuccess = false,
                        FileName = "",
                        Result = ConstantStrings.ExtensionImageSupport,
                        ImageThumbnail = ""
                    };
                }

                if (fileimage.ContentLength > Maxlengthfile)
                {
                    return new UploadResult
                    {
                        IsSuccess = false,
                        FileName = "",
                        Result = ConstantStrings.MaxLengthFileSupport,
                        ImageThumbnail = ""
                    };
                }
                CreateFolder(Rootimage);
                var filename = string.Format("{0}.{1}", GetStringTimes.GetTimes(DateTime.Now), ExtentionFile.GetExtentionFileImageString(fileimage.FileName.ToLower()));
                fileimage.SaveAs(GetTempUploadImagePath(filename));
                GenerateThumbNail(filename, Heightthumbnail);
                return new UploadResult
                {
                    IsSuccess = true,
                    FileName = filename,
                    Result = ConstantStrings.UploadSuccess,
                    ImageThumbnail = filename
                };

            }
            catch (Exception)
            {
                return new UploadResult
                {
                    IsSuccess = false,
                    FileName = "",
                    Result = ConstantStrings.UploadNonSuccess,
                    ImageThumbnail = ""
                };
            }
        }
开发者ID:ZenHiro,项目名称:itdtv,代码行数:60,代码来源:Upload.cs


示例17: AddFileToTitle

        public ActionResult AddFileToTitle(string wikiname, int tid,HttpPostedFileBase file, ViewTitleFile mod)
        {
            try
            {
                if (CommonTools.isEmpty(wikiname) && tid <= 0)
                {
                    return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
                }
                mod.File = new WikiFile();
                WikiTitle title = CommonTools.titlemngr.GetTitlebyId(wikiname, tid);
                mod.Title = title;
                if ( mod !=null && mod.File !=null && mod.Title !=null && file.ContentLength>0)
                {
                    WikiFile fmod = mod.File;

                    this.filemngr.AddFile(wikiname, mod.File, file, tid, CommonTools.usrmng.GetUser(this.User.Identity.Name));
                }
                return View(mod);
            }
            catch (Exception ex)
            {

                CommonTools.ErrorReporting(ex);
                return new HttpStatusCodeResult(System.Net.HttpStatusCode.InternalServerError);
            }
        }
开发者ID:angaratosurion,项目名称:MultiPlex,代码行数:26,代码来源:WikiFileController.cs


示例18: Upload

        public ActionResult Upload(HttpPostedFileBase upload)
        {
            if (upload == null)
            {
                ModelState.AddModelError("upload", "Please select a file");
            }
            else
            {
                string extension = Path.GetExtension(upload.FileName);
                if (!(extension ?? "").Equals(".nupkg", StringComparison.CurrentCultureIgnoreCase))
                {
                    ModelState.AddModelError("upload", "Invalid extension. Only .nupkg files will be accepted.");
                }
            }

            if (ModelState.IsValid)
            {
                var path = Path.Combine(Server.MapPath("~/Packages"), upload.FileName);
                upload.SaveAs(path);
                ViewBag.StatusMessage = new StatusMessage
                                            {
                                                Success = true,
                                                Message = String.Format("{0} was uploaded successfully.", upload.FileName)
                                            };
            }

            return View("Index");
        }
开发者ID:h82258652,项目名称:NugetServer,代码行数:28,代码来源:HomeController.cs


示例19: ThemeUploader

 public ThemeUploader(string tenant, HttpPostedFileBase postedFile)
 {
     this.Tenant = tenant;
     this.PostedFile = postedFile;
     this.ThemeInfo = new ThemeInfo();
     this.SetUploadPaths();
 }
开发者ID:frapid,项目名称:frapid,代码行数:7,代码来源:ThemeUploader.cs


示例20: Create

        public ActionResult Create(Student student, HttpPostedFileBase upload)
        {
            var db = DAL.DbContext.Create();

                if (ModelState.IsValid)
                {
                    if (StudentValidate(student))
                    {
                        if (upload != null && upload.ContentLength > 0)
                        {
                            using (var reader = new System.IO.BinaryReader(upload.InputStream))
                            {
                                student.Image = reader.ReadBytes(upload.ContentLength);
                            }

                            var studentId = db.Students.Insert(student);

                            if (studentId.HasValue && studentId.Value > 0)
                            {
                                return RedirectToAction("Index");
                            }
                            else
                            {
                                return View(student);
                            }
                    }
                }
            }

                //ViewBag.Id = new SelectList(db.GetCourses().Distinct().ToList(), "Id", "CourseAbbv");
                ViewBag.CourseID = new SelectList(db.Courses.All(), "Id", "CourseAbbv", student.CourseID);
                ViewBag.CollegeID = new SelectList(db.Colleges.All(), "Id", "CollegeName", student.CollegeID);

            return View(student);
        }
开发者ID:heyd1203,项目名称:WMSURFIDSYS,代码行数:35,代码来源:StudentController.cs



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
C# Web.HttpRequest类代码示例发布时间:2022-05-26
下一篇:
C# Web.HttpPostedFile类代码示例发布时间: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