當前位置: 首頁>>代碼示例>>C#>>正文


C# Web.HttpPostedFileBase類代碼示例

本文整理匯總了C#中System.Web.HttpPostedFileBase的典型用法代碼示例。如果您正苦於以下問題:C# HttpPostedFileBase類的具體用法?C# HttpPostedFileBase怎麽用?C# HttpPostedFileBase使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


HttpPostedFileBase類屬於System.Web命名空間,在下文中一共展示了HttpPostedFileBase類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的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


注:本文中的System.Web.HttpPostedFileBase類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。