本文整理匯總了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;
}
示例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;
}
}
示例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 });
}
示例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 "";
}
示例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);
}
示例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);
}
示例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();
}
}
示例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);
}
示例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);
}
示例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 });
}
示例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;
}
示例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);
}
示例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));
}
}
示例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();
}