public static int AddImage(HttpPostedFileBase UploadImage, ref ApplicationDbContext _context) { int imageId; if (UploadImage != null) { Models.File image = new Models.File { Content = ReduceSize(UploadImage.InputStream, 210, 300, ref _context), AdditionalData = ReduceSize(UploadImage.InputStream, 70, 100, ref _context), ImageMimeType = UploadImage.ContentLength }; _context.Files.Add(image); _context.SaveChanges(); imageId = image.Id; } else { imageId = GlobalVariables.DefaultImageId; } return(imageId); }
public ActionResult Create(string Name, HttpPostedFileBase File) { int projectID = (int)Session["projectID"]; int userID = (int)Session["userID"]; Models.File file = new Models.File(); file.Date_Uploaded = DateTime.Now; file.Name = Name; file.ID_Project = projectID; file.ID_User = userID; file.ID_File_Type = GetTypeID(File); file.TypeFile = Path.GetExtension(File.FileName).Substring(1); file.Path = SaveFile(File); file.Length = GetLength(File); try { db.Files.Add(file); db.SaveChanges(); NotificationSystem.SendNotification(EnumNotification.CREATE_FILE, "/Storage"); } catch (Exception ex) { Console.WriteLine(ex.Message); } return(RedirectToAction("Index")); }
public ActionResult UpdateFile(Models.File file) { try { if (file != null) { db.Files.Update(file); db.SaveChanges(); if (file.ChairId != null) { return(View("ChairPartial", db.Chairs.Include(l => l.Folders).Include(fl => fl.Files).Include(c => c.Advertisements).Single(a => a.Id == file.ChairId))); } else { return(View("Folder", db.Folders.Include(l => l.Folders).Include(fl => fl.Files).Single(a => a.Id == file.FolderId))); } } else { return(BadRequest()); } } catch (Exception e) { return(BadRequest("Помилка запиту (" + e.Message + ")")); } }
public ActionResult Save(FormCollection formCollection) { if (Request != null) { HttpPostedFileBase file = Request.Files["UploadedFile"]; string tareaID = Request.Form["AssignmentId"]; if ((file != null) && (file.ContentLength > 0) && !string.IsNullOrEmpty(file.FileName)) { string fileName = file.FileName; string fileContextType = file.ContentType; int assignmentId = Convert.ToInt32(tareaID); byte[] fileBytes = new byte[file.ContentLength]; file.InputStream .Read(fileBytes, 0, Convert.ToInt32(file.ContentLength)); var entity = new Models.File { FileName = fileName, ContentType = fileContextType, fileBytes = fileBytes, AssignmentId = assignmentId }; db.Files.Add(entity); db.SaveChanges(); } } var files = db.Files.ToList(); return(View("Index", "files", null)); }
public ActionResult UploadFile(int?id, Models.File file, IFormFile f) { //int? blogId_ = HttpContext.Session.GetInt32(sessionId_); file.BlogId = id; file.Id = 0; var path = Path.Combine(filePath, f.FileName); file.Path = path.ToString(); //context_.Files.Add(file); //context_.SaveChanges(); Blog blog = context_.Blogs.Find(id); if (blog.Files == null) { blog.Files = new List <Models.File>(); } blog.Files.Add(file); context_.SaveChanges(); var fileStream = new FileStream(path, FileMode.Create); f.CopyToAsync(fileStream); return(RedirectToAction("Index")); }
public HttpResponseMessage SaveFile() { //Create HTTP Response. HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK); //Check if Request contains File. if (HttpContext.Current.Request.Files.Count == 0) { throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType); } //Read the File data from Request.Form collection. HttpPostedFile postedFile = HttpContext.Current.Request.Files[0]; //Convert the File data to Byte Array. byte[] bytes; using (BinaryReader br = new BinaryReader(postedFile.InputStream)) { bytes = br.ReadBytes(postedFile.ContentLength); } //Insert the File to Database Table. UploadDownloadEntities entities = new UploadDownloadEntities(); Models.File file = new Models.File { Name = Path.GetFileName(postedFile.FileName), ContentType = postedFile.ContentType, Data = bytes }; entities.Files.Add(file); entities.SaveChanges(); return(Request.CreateResponse(HttpStatusCode.OK, new { id = file.id, Name = file.Name })); }
public async Task <File> SelectByIdAsync(int id) { Models.File file = null; using (var context = _dbContext) { file = await context.ExecuteReaderAsync <Models.File>( CommandType.StoredProcedure, "SelectFileById", async reader => { if ((reader != null) && reader.HasRows) { await reader.ReadAsync(); file = new Models.File(); file.PopulateModel(reader); } return(file); }, new IDbDataParameter[] { new DbParam("Id", DbType.Int32, id) }); } return(file); }
public Models.File Put(int id, [FromBody] Models.File file) { var File = _files.GetFile(file.FileId, false); if (ModelState.IsValid && File != null && File.Folder.SiteId == _alias.SiteId && _userPermissions.IsAuthorized(User, EntityNames.Folder, file.FolderId, PermissionNames.Edit)) { if (File.Name != file.Name || File.FolderId != file.FolderId) { string folderpath = _folders.GetFolderPath(file.Folder); if (!Directory.Exists(folderpath)) { Directory.CreateDirectory(folderpath); } System.IO.File.Move(_files.GetFilePath(File), Path.Combine(folderpath, file.Name)); } file.Extension = Path.GetExtension(file.Name).ToLower().Replace(".", ""); file = _files.UpdateFile(file); _logger.Log(LogLevel.Information, this, LogFunction.Update, "File Updated {File}", file); } else { _logger.Log(LogLevel.Error, this, LogFunction.Security, "Unauthorized File Put Attempt {File}", file); HttpContext.Response.StatusCode = (int)HttpStatusCode.Forbidden; file = null; } return(file); }
public void Delete(int id) { Models.File file = _files.GetFile(id); if (file != null && file.Folder.SiteId == _alias.SiteId && _userPermissions.IsAuthorized(User, EntityNames.Folder, file.Folder.FolderId, PermissionNames.Edit)) { _files.DeleteFile(id); string filepath = _files.GetFilePath(file); if (System.IO.File.Exists(filepath)) { // remove file and thumbnails foreach (var f in Directory.GetFiles(Path.GetDirectoryName(filepath), Path.GetFileNameWithoutExtension(filepath) + ".*")) { System.IO.File.Delete(f); } } _logger.Log(LogLevel.Information, this, LogFunction.Delete, "File Deleted {File}", file); } else { _logger.Log(LogLevel.Error, this, LogFunction.Security, "Unauthorized File Delete Attempt {FileId}", id); HttpContext.Response.StatusCode = (int)HttpStatusCode.Forbidden; } }
private Models.File CreateFile(string filename, int folderid, string filepath) { Models.File file = new Models.File(); file.Name = filename; file.FolderId = folderid; FileInfo fileinfo = new FileInfo(filepath); file.Extension = fileinfo.Extension.ToLower().Replace(".", ""); file.Size = (int)fileinfo.Length; file.ImageHeight = 0; file.ImageWidth = 0; if (Constants.ImageFiles.Split(',').Contains(file.Extension.ToLower())) { FileStream stream = new FileStream(filepath, FileMode.Open, FileAccess.Read); using (var image = Image.FromStream(stream)) { file.ImageHeight = image.Height; file.ImageWidth = image.Width; } stream.Close(); } return(file); }
public void Delete(int id) { Models.File file = _files.GetFile(id); if (file != null) { if (_userPermissions.IsAuthorized(User, EntityNames.Folder, file.Folder.FolderId, PermissionNames.Edit)) { _files.DeleteFile(id); string filepath = Path.Combine(GetFolderPath(file.Folder), file.Name); if (System.IO.File.Exists(filepath)) { System.IO.File.Delete(filepath); } _logger.Log(LogLevel.Information, this, LogFunction.Delete, "File Deleted {File}", file); } else { _logger.Log(LogLevel.Error, this, LogFunction.Delete, "User Not Authorized To Delete File {FileId}", id); HttpContext.Response.StatusCode = 401; } } else { _logger.Log(LogLevel.Error, this, LogFunction.Delete, "File Not Found {FileId}", id); HttpContext.Response.StatusCode = 404; } }
public Models.File LoadByArtworkId(int id) { if (id != null) { List <Models.File> files = new List <Models.File>(); BL.Artwork artwork = new BL.Artwork(); var file = db.Files.FirstOrDefault(f => f.ArtworkId == id); if (file != null) { Models.File f = new Models.File { Id = file.Id, ArtworkId = file.ArtworkId, UserId = file.UserId, Content = file.Content, ContentType = file.ContentType, FileName = file.FileName, Artwork = artwork.LoadById(file.ArtworkId) }; return(f); } else { return(null); } } else { return(null); } }
public async Task <IActionResult> AddFile(IFormFile uploadedFile) { if (uploadedFile != null) { // путь к папке Files string path = "/Files/" + uploadedFile.FileName; // сохраняем файл в папку Files в каталоге wwwroot using (var fileStream = new FileStream(_appEnvironment.WebRootPath + path, FileMode.Create)) { await uploadedFile.CopyToAsync(fileStream); } Models.File file = new Models.File { Name = uploadedFile.FileName, Path = path }; try { file.Value = System.IO.File.ReadAllText(_appEnvironment.WebRootPath + path, Encoding.GetEncoding(CodePage)); FileViewModel.Text = file.Value; } catch (Exception) { } _context.Files.Add(file); _context.SaveChanges(); } return(RedirectToAction("Index")); }
private List<Models.File> DownloadRepoFiles(string downloadUrl) { List<Models.File> results = new List<Models.File>(); using (var wc = new WebClient()) { byte[] tarball = wc.DownloadData(downloadUrl); using (var zip = ZipFile.Read(new MemoryStream(tarball))) { string dir = ""; if (zip.Count > 0) { dir = zip[0].FileName; } foreach (var file in zip) { if (!file.IsDirectory) { var fileStream = new MemoryStream(); file.Extract(fileStream); byte[] content = fileStream.ToArray(); string filename = file.FileName.Replace(dir, ""); Models.File repositoryFile = new Models.File { Content = content, Filename = filename, Size = content.Length, Include = true }; results.Add(repositoryFile); } } } } return results; }
public ActionResult CreateItem([Bind(Include = "ShoppingListItemId,ShoppingListId," + "Content,Priority,Note,IsChecked,CreatedUtc,ModifiedUtc")] ShoppingListItem shoppingListItem, int id, HttpPostedFileBase upload) { //added parameter int id to "create". if (ModelState.IsValid) { //add shoppinglistitems to a particular list prior to "add" if (upload != null && upload.ContentLength > 0) { var avatar = new Models.File { FileName = System.IO.Path.GetFileName(upload.FileName), FileType = FileType.Avatar, ContentType = upload.ContentType }; using (var reader = new System.IO.BinaryReader(upload.InputStream)) { avatar.Content = reader.ReadBytes(upload.ContentLength); } shoppingListItem.Files = new List <Models.File> { avatar }; } shoppingListItem.ShoppingListId = id; db.ShoppingListItems.Add(shoppingListItem); db.SaveChanges(); return(RedirectToAction("ViewItem", new { id })); } //trying to return to view of shopping list items on a particular list return(View()); }
public ActionResult AddEBook(EBook model, HttpPostedFileBase file) { int fileId = 0; if (file != null) { string fileName = Path.Combine(Request.MapPath("~/Upload"), DateHelper.GetTimeStamp() + Path.GetFileName(file.FileName)); file.SaveAs(fileName); Models.File _file = new Models.File(); _file.FileTypeID = model.EBookTypeID; _file.Path = DateHelper.GetTimeStamp() + Path.GetFileName(file.FileName); _file.Time = DateTime.Now; _file.ContentType = file.ContentType; _file.FileName = file.FileName; _file.FileSize = file.ContentLength.ToString(); db.Files.Add(_file); db.SaveChanges(); fileId = _file.ID; EBook Ebook = new EBook(); Ebook.Browses = 0; Ebook.Title = model.Title; Ebook.Description = model.Description; Ebook.EBookTypeID = model.EBookTypeID; Ebook.FileID = fileId; Ebook.Time = DateTime.Now; Ebook.UserID = CurrentUser.ID; db.EBooks.Add(Ebook); db.SaveChanges(); return RedirectToAction("EBookManager"); } else { return Redirect("/Admin/AdminMessage?msg=文件不能为空"); } }
private async Task <List <Models.File> > SearchOneDrive(string search, string token) { List <Models.File> files = new List <Models.File>(); using (HttpClient client = new HttpClient()) { client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token); var result = await client.GetAsync("https://graph.microsoft.com/v1.0/me/drive/root/search(q='" + HttpUtility.UrlEncode(search) + "')"); var resultString = await result.Content.ReadAsStringAsync(); var jResult = JObject.Parse(resultString); JArray jFiles = (JArray)jResult["value"]; foreach (JObject item in jFiles) { Models.File f = new Models.File(); f.CreatedBy = item["createdBy"]["user"].Value <string>("displayName"); f.CreatedDate = DateTimeOffset.Parse(item.Value <string>("createdDateTime")); f.ID = item.Value <string>("id"); f.LastModifiedBy = item["lastModifiedBy"]["user"].Value <string>("displayName"); f.LastModifiedDate = DateTimeOffset.Parse(item.Value <string>("lastModifiedDateTime")); f.Name = item.Value <string>("name"); f.WebURL = item.Value <string>("webUrl"); files.Add(f); if (files.Count > 10) { return(files); } } return(files); } }
public ActionResult DLFile(string DlPath) { var DL = new Models.Download { Filename = DlPath, DownloadDate = System.DateTime.Now, IPAddress = HttpContext.Request.UserHostAddress }; var file = new Models.File(DlPath); if (ModelState.IsValid) { DLTrack.Downloads.Add(DL); DLTrack.SaveChanges(); } try { var fileData = FileDownloadInMvc3.Models.ExtensionMethods.GetFileData(file.Name, file.Path); return new FileDownloadResult(file.Name, fileData); } catch (FileNotFoundException) { throw new HttpException(404, string.Format("The file {0} was not found.", file)); } //return View(DL); }
public async Task <Models.File> InsertUpdateAsync(Models.File model) { var id = await InsertUpdateInternal( model.Id, model.FeatureId, model.Name, model.Alias, model.Extension, model.ContentBlob, model.ContentType, model.ContentLength, model.ContentGuid, model.ContentCheckSum, model.TotalViews, model.CreatedUserId, model.CreatedDate, model.ModifiedUserId, model.ModifiedDate); if (id > 0) { return(await SelectByIdAsync(id)); } return(null); }
public ActionResult Files(string FilePath) { ViewBag.Message = "File Info"; var file = new Models.File(FilePath); return View(file); }
public async Task <IPagedResults <File> > SelectAsync(IDbDataParameter[] dbParams) { IPagedResults <File> output = null; using (var context = _dbContext) { output = await context.ExecuteReaderAsync <IPagedResults <File> >( CommandType.StoredProcedure, "SelectFilesPaged", async reader => { if ((reader != null) && (reader.HasRows)) { output = new PagedResults <File>(); while (await reader.ReadAsync()) { var entity = new Models.File(); entity.PopulateModel(reader); output.Data.Add(entity); } if (await reader.NextResultAsync()) { await reader.ReadAsync(); output.PopulateTotal(reader); } } return(output); }, dbParams); } return(output); }
public void AddWorkWithSingleFile(CreateWorkDto createWork) { var work = new Work { Title = createWork.Title, Description = createWork.Description, workStatus = WorkStatus.Pendding, DeveloperId = createWork.DeveloperId, SprintTaskId = createWork.SprintTaskId, }; db.Works.Add(work); db.SaveChanges(); Stream st = createWork.TheFile.OpenReadStream(); // strem file inside it using (BinaryReader br = new BinaryReader(st))//binary reader stream inside it { var byteFile = br.ReadBytes((int)st.Length); var file = new Models.File(); file.FileName = createWork.TheFile.FileName; file.FileExtension = createWork.TheFile.ContentType; file.FileBytes = byteFile; file.WorkId = work.Id; db.Files.Add(file); db.SaveChanges(); } db.SaveChanges(); }
public static Guid?CreateImage(HttpPostedFileBase uploadPicture) { try { Guid avatarGuid = System.Guid.NewGuid(); var avatar = new Models.File { FileNumber = System.IO.Path.GetFileName(uploadPicture.FileName), FileID = avatarGuid, FileDescription = uploadPicture.ContentType }; avatar.FileNumber = avatar.FileNumber.Substring(0, Math.Min(avatar.FileNumber.Length, 45)); using (var reader = new System.IO.BinaryReader(uploadPicture.InputStream)) { avatar.ItemImage = reader.ReadBytes(uploadPicture.ContentLength); } db.Files.Add(avatar); db.SaveChanges(); return(avatarGuid); } catch (Exception ex) { //log } return(null); }
// download files public ActionResult Download(int id) { var authData = HttpContext.Session.GetString("userInfo"); if (authData != "") { User user = JsonConvert.DeserializeObject <User>(authData); if (userAccess.HasAccess(user.Id, 1, user.DesignationId)) { Models.File file = fileManager.GetFileById(id); WebClient client = new WebClient(); var buffer = client.DownloadData(file.Url); return(File(buffer, file.FileExtension, file.FileName)); } else { return(RedirectToAction("AccessDenied", "Home")); } } else { HttpContext.Session.SetString("userInfo", ""); return(RedirectToAction("Login", "LogIn")); } }
public IActionResult Index(IFormFile files) { if (files != null) { if (files.Length > 0) { //Getting FileName var fileName = Path.GetFileName(files.FileName); //Getting file Extension var fileExtension = Path.GetExtension(fileName); // concatenating FileName + FileExtension var newFileName = String.Concat(Convert.ToString(Guid.NewGuid()), fileExtension); var objfiles = new Models.File() { DocumentId = Guid.NewGuid(), Name = newFileName, FileType = fileExtension, CreatedOn = DateTime.Now }; using (var target = new MemoryStream()) { files.CopyTo(target); objfiles.DataFiles = target.ToArray(); } _context.Files.Add(objfiles); _context.SaveChanges(); } } return(View()); }
public ActionResult EditEntryView(EntryViewModel model, int postId, string Title, string Content, int?fileId) { var ctx = new AppDbContext(); var ThisFile = new Models.File(); if (fileId != null) { var OldFile = ctx.Files.Find(fileId); var CurrentEntry = ctx.Entries.Find(postId); model.entry = new Entry(); model.entry.Title = Title; model.entry.Content = Content; model.entry.Id = postId; model.entry.fileId = OldFile.FileId; } else { var CurrentEntry = ctx.Entries.Find(postId); model.entry = new Entry(); model.entry.Title = Title; model.entry.Content = Content; model.entry.Id = postId; } return(View(model)); }
public async Task <IActionResult> Edit(Guid id, [Bind("Id,FileName,UploadDate,Records")] Models.File file) { if (id != file.Id) { return(NotFound()); } if (ModelState.IsValid) { try { _context.Update(file); await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!FileExists(file.Id)) { return(NotFound()); } else { throw; } } return(RedirectToAction(nameof(Index))); } return(View(file)); }
public ActionResult SaveFileToDatabase(int id, HttpPostedFileBase file) { int fileSize = file.ContentLength; string fileExt = Path.GetExtension(file.FileName).ToUpper(); if (fileExt == ".PDF" || fileExt == ".RAR" || fileExt == ".ZIP") { //get the bytes from the uploaded file byte[] data = GetBytesFromFile(file); var fileToSave = new Models.File { ProjectId = id, FileName = file.FileName, FileContent = data, ContentType = file.ContentType, UploadedDate = DateTime.Now, Size = fileSize }; _context.Files.Add(fileToSave); _context.SaveChanges(); } return(RedirectToAction("UploadFileForProject/" + id, "Projects")); }
public IActionResult DeleteFile(Models.File file) { try { if (file != null) { db.Files.Remove(file); db.SaveChanges(); string path = _appEnvironment.WebRootPath + HttpUtility.UrlDecode(file.Path); if (System.IO.File.Exists(path)) { System.IO.File.Delete(path); } if (file.ChairId != null) { return(View("ChairPartial", db.Chairs.Include(l => l.Folders).Include(fl => fl.Files).Include(c => c.Advertisements).Single(a => a.Id == file.ChairId))); } else { return(View("Folder", db.Folders.Include(l => l.Folders).Include(fl => fl.Files).Single(a => a.Id == file.FolderId))); } } else { return(BadRequest()); } } catch (Exception e) { return(BadRequest("Помилка запиту (" + e.Message + ")")); } }
public ActionResult DeleteConfirmed(int id) { Models.File file = db.Files.Find(id); db.Files.Remove(file); db.SaveChanges(); return(RedirectToAction("Index")); }
public ActionResult Index(HttpPostedFileBase file) { var ext = Path.GetExtension(file.FileName); var pdf = ".pdf"; if (!file.FileName.Contains(pdf)) { return(View("Contact")); /*make this something else*/ } else { if (file != null && file.ContentLength > 0) { var id = User.Identity.GetUserId(); var user = db.JobSeeker.Where(x => x.UserId == id).Select(x => x).FirstOrDefault(); var fileName = Path.GetFileName(id + ".pdf"); var path = Path.Combine(Server.MapPath("~/Resumes"), fileName); Models.File aResume = new Models.File(); aResume.FileName = user.UserId; db.File.Add(aResume); user.UploadedResume = true; db.SaveChanges(); user.ResumeID = aResume.FileID; db.SaveChanges(); file.SaveAs(path); } return(RedirectToAction("Index")); } }
public async Task <ActionResult> PostFile() { var file = Request.Form.Files[0]; if (file == null || file.Length == 0) { return(Content("file not selected")); } var path = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot"); if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } path = Path.Combine(Path.Combine(Directory.GetCurrentDirectory(), "wwwroot"), file.FileName); using (var stream = new FileStream(path, FileMode.Create)) { await file.CopyToAsync(stream); } Models.File f = new Models.File(); f.name = file.Name; f.size = Convert.ToInt32(file.Length); f.folderId = 0; f.path = path; _context.files.Add(f); _context.SaveChanges(); return(StatusCode(200)); }
public ActionResult Create(Project project, HttpPostedFileBase upload) { Models.File file = new Models.File(); string filename; if (upload != null && ModelState.IsValid) { file.file_data = new byte[upload.ContentLength]; upload.InputStream.Read(file.file_data, 0, upload.ContentLength); file.name = upload.FileName; file.file_type = upload.ContentType; filename = upload.FileName; upload.SaveAs(Server.MapPath("~/Content/img/" + upload.FileName)); db.Files.Add(file); db.SaveChanges(); var selectedFile = db.Files.SingleOrDefault(f => f.name == filename); project.file_id = selectedFile.Id; db.Projects.Add(project); db.SaveChanges(); return(RedirectToAction("Index")); } else { return(HttpNotFound()); } }
public Models.File Put(int id, [FromBody] Models.File file) { if (ModelState.IsValid && _userPermissions.IsAuthorized(User, EntityNames.Folder, file.FolderId, PermissionNames.Edit)) { file.Folder = _folders.GetFolder(file.FolderId); Models.File _file = _files.GetFile(id, false); if (_file.Name != file.Name || _file.FolderId != file.FolderId) { string folderpath = GetFolderPath(file.Folder); if (!Directory.Exists(folderpath)) { Directory.CreateDirectory(folderpath); } System.IO.File.Move(Path.Combine(GetFolderPath(_file.Folder), _file.Name), Path.Combine(folderpath, file.Name)); } file.Extension = Path.GetExtension(file.Name).ToLower().Replace(".", ""); file = _files.UpdateFile(file); _logger.Log(LogLevel.Information, this, LogFunction.Update, "File Updated {File}", file); } else { _logger.Log(LogLevel.Error, this, LogFunction.Update, "User Not Authorized To Update File {File}", file); HttpContext.Response.StatusCode = 401; file = null; } return(file); }
public DownloadAction(FileSupport fileSupport, Client.ShareFileClient client, int downloadId, Models.File child, FileSystemInfo target, ActionType type) { this.child = child; this.client = client; this.downloadId = downloadId; this.target = target; this.actionType = type; this.fileSupportDelegate = fileSupport; }
public async Task<Models.File> Upload() { // Set the file stream postion to the start of the stream File.InputStream.Position = 0; // Create extension, unique key and file hash variables, and reset position after reading stream var extension = Path.GetExtension(File.FileName); var key = string.Format("File-{0}{1}", Guid.NewGuid(), extension); var hash = new MD5Cng().ComputeHash(File.InputStream); File.InputStream.Position = 0; // Check if the file already exists in the Database using the hash; Return the existing file object if the file exists already if (_ctx.Files.Any(m => m.Md5 == hash && m.Container == Container)) { return _ctx.Files.Single(m => m.Md5 == hash && m.Container == Container); } // Get / create the blob container reference _container = _blobClient.GetContainerReference(Container); _container.CreateIfNotExists(); _container.SetPermissions( new BlobContainerPermissions { PublicAccess = BlobContainerPublicAccessType.Blob }); // Create new database object to reference the blob from var fileEntity = new Models.File { Name = File.FileName.Replace(extension ?? "", ""), ContentLength = File.ContentLength, ContentType = File.ContentType, Key = key, Container = Container, Md5 = hash }; _ctx.Files.Add(fileEntity); await _ctx.SaveChangesAsync(); // Upload original file var block = _container.GetBlockBlobReference(fileEntity.Key); block.Properties.ContentType = fileEntity.ContentType; await block.UploadFromStreamAsync(File.InputStream); // Upload resized image versions await UploadImageResized(fileEntity); return fileEntity; }
public ActionResult Create(Advertisement advertisement, HttpPostedFileBase[] fileUpload2, HttpPostedFileBase[] fileUpload, string[] description, int? cat) { try { if (ModelState.IsValid) { using (var db = new ApplicationDbContext()) { if(!checkBannedWords(advertisement.Title)||!checkBannedWords(advertisement.Content)) { return RedirectToAction("Index"); // TU DODAAC CO MA SIE STAC } foreach(var desc in description) { if(!checkBannedWords(desc)) { return RedirectToAction("Index"); // TU DODAAC CO MA SIE STAC } } string login = User.Identity.GetUserName(); var user = db.Users.FirstOrDefault(u => u.UserName==login); advertisement.User = user; advertisement.UserId = user.Id; advertisement.CategoryId = 1; advertisement.Category = db.Category.FirstOrDefault(u => u.CategoryId == 1); advertisement.AddedDate = DateTime.Now; db.Advertisement.Add(advertisement); db.SaveChanges(); int lastItemId = db.Advertisement.Max(item => item.AdvertisementId); if (!Directory.Exists(Server.MapPath("~/advertisements"))) { Directory.CreateDirectory(Server.MapPath("~/advertisements")); } Directory.CreateDirectory(Server.MapPath("~/advertisements/" + lastItemId)); foreach (var file in fileUpload2) { String pathToDb = "~/advertisements/" + lastItemId + "/" + file.FileName; String path = Server.MapPath(pathToDb); file.SaveAs(path); Models.File newFile = new Models.File(); newFile.AdvertisementId = lastItemId; newFile.Advertisement = advertisement; newFile.Path = pathToDb; newFile.InDetails = true; db.File.Add(newFile); db.SaveChanges(); } foreach (var file in fileUpload) { int i = 0; String pathToDb = "~/advertisements/" + lastItemId + "/" + file.FileName; String path = Server.MapPath(pathToDb); file.SaveAs(path); Models.File newFile = new Models.File(); newFile.AdvertisementId = lastItemId; newFile.Advertisement = advertisement; newFile.Path = pathToDb; newFile.InDetails = false; if (description[i] != "") newFile.Description = description[i]; else newFile.Description = null; db.File.Add(newFile); db.SaveChanges(); i++; } } return RedirectToAction("Index"); } return RedirectToAction("Index"); } catch { return View(); } }
public ActionResult AddEBook(EBook model, HttpPostedFileBase file, HttpPostedFileBase file1) { var random = DateHelper.GetTimeStamp(); int fileId = 0; if (file != null) { string fileName = Path.Combine(Request.MapPath("~/Upload/EBook"), random + Path.GetExtension(file.FileName)); file.SaveAs(fileName); Models.File _file = new Models.File(); _file.FileTypeID = model.EBookTypeID; _file.Path = random + Path.GetExtension(file.FileName); _file.Time = DateTime.Now; _file.ContentType = file.ContentType; _file.FileName = file.FileName; _file.FileSize = file.ContentLength.ToString(); db.Files.Add(_file); db.SaveChanges(); fileId = _file.ID; EBook Ebook = new EBook(); Ebook.Browses = 0; Ebook.Title = model.Title; Ebook.Description = model.Description; Ebook.EBookTypeID = model.EBookTypeID; Ebook.FileID = fileId; Ebook.Time = DateTime.Now; Ebook.UserID = CurrentUser.ID; Ebook.Author = model.Author; System.IO.Stream stream = file1.InputStream; byte[] buffer = new byte[stream.Length]; stream.Read(buffer, 0, (int)stream.Length); stream.Close(); Ebook.Picture = buffer; db.EBooks.Add(Ebook); db.SaveChanges(); return RedirectToAction("EBookManager"); } else { return Redirect("/Admin/AdminMessage?msg=文件不能为空"); } }
//DONT USE THIS IF YOU NEED TO ALLOW LARGE FILES UPLOADS //Credit to i-e-b and his ASP.Net uploader for the bulk of the upload helper methods - https://github.com/i-e-b/jQueryFileUpload.Net private void UploadWholeFile(int articleId,HttpRequestBase request, List<ViewDataUploadFilesResult> statuses) { for (int i = 0; i < request.Files.Count; i++) { var file = request.Files[i]; byte[] buffer = new byte[file.ContentLength]; file.InputStream.Read(buffer, 0, file.ContentLength); var f = new Models.File { ArticleId = articleId, Filename = file.FileName, Size = file.ContentLength }; context.Files.Add(f); context.SaveChanges(); var filePath = ModelHelpers.createFilePath(f); c.UploadFile("/", filePath, buffer); statuses.Add(new ViewDataUploadFilesResult() { name = file.FileName, size = file.ContentLength, type = file.ContentType, url = "Download?id=" + f.FileId, delete_url = "Delete?id=" + f.FileId, delete_type = "GET", }); } }
public ActionResult AddLink(ResourceLink model, HttpPostedFileBase file) { int fileId = 0; if (model.IsHaveFile) { string fileName = Path.Combine(Request.MapPath("~/Upload"), DateHelper.GetTimeStamp() + Path.GetFileName(file.FileName)); file.SaveAs(fileName); Models.File _file = new Models.File(); _file.FileTypeID = model.LinkTypeID; _file.Path = DateHelper.GetTimeStamp() + Path.GetFileName(file.FileName); _file.Time = DateTime.Now; _file.ContentType = file.ContentType; _file.FileName = file.FileName; _file.FileSize = file.ContentLength.ToString(); db.Files.Add(_file); db.SaveChanges(); fileId = _file.ID; } ResourceLink link = new ResourceLink(); link.IsHaveFile = model.IsHaveFile; link.LinkTypeID = model.LinkTypeID; link.Time = DateTime.Now; link.Title = model.Title; link.URL = model.URL; link.UserID = CurrentUser.ID; link.FileID = fileId; db.ResourceLinks.Add(link); db.SaveChanges(); return RedirectToAction("LinkManager"); }
public ActionResult EBookDelete(int id) { EBook book = new EBook(); Models.File file = new Models.File(); book = db.EBooks.Find(id); file = db.Files.Find(book.FileID); var path = Server.MapPath("~/Upload/" + file.Path); System.IO.File.Delete(path); db.Files.Remove(file); db.EBooks.Remove(book); db.SaveChanges(); return Content("ok"); }
public ActionResult EBookEdit(EBook model, HttpPostedFileBase file) { EBook book = new EBook(); book = db.EBooks.Find(model.ID); book.Title = model.Title; book.Description = model.Description; book.EBookTypeID = model.EBookTypeID; if (file != null) { Models.File _file = new Models.File(); _file = db.Files.Find(book.FileID); var path = Server.MapPath("~/Upload/" + _file.Path); System.IO.File.Delete(path); string fileName = Path.Combine(Request.MapPath("~/Upload"), DateHelper.GetTimeStamp() + Path.GetFileName(file.FileName)); file.SaveAs(fileName); _file.Path = DateHelper.GetTimeStamp() + Path.GetFileName(file.FileName); _file.ContentType = file.ContentType; _file.FileName = file.FileName; _file.FileSize = file.ContentLength.ToString(); } db.SaveChanges(); return RedirectToAction("EBookManager"); }
public ActionResult LinkDelete(int id) { ResourceLink link = new ResourceLink(); link = db.ResourceLinks.Find(id); db.ResourceLinks.Remove(link); if (link.IsHaveFile) { Models.File file = new Models.File(); file = db.Files.Find(link.FileID); var path = Server.MapPath("~/Upload/" + file.Path); System.IO.File.Delete(path); db.Files.Remove(file); } db.SaveChanges(); return Content("ok"); }
public ActionResult LinkEdit(ResourceLink model, HttpPostedFileBase file) { int fileId = 0; if (file != null && model.IsHaveFile) { if (model.FileID != 0) { string fileName = Path.Combine(Request.MapPath("~/Upload"), DateHelper.GetTimeStamp() + Path.GetFileName(file.FileName)); file.SaveAs(fileName); Models.File _file = new Models.File(); _file = db.Files.Find(model.FileID); _file.FileTypeID = model.LinkTypeID; _file.Path = DateHelper.GetTimeStamp() + Path.GetFileName(file.FileName); _file.ContentType = file.ContentType; _file.FileName = file.FileName; _file.FileSize = file.ContentLength.ToString(); db.SaveChanges(); fileId = _file.ID; } else { string fileName = Path.Combine(Request.MapPath("~/Upload"), DateHelper.GetTimeStamp() + Path.GetFileName(file.FileName)); file.SaveAs(fileName); Models.File _file = new Models.File(); _file.FileTypeID = model.LinkTypeID; _file.Path = DateHelper.GetTimeStamp() + Path.GetFileName(file.FileName); _file.Time = DateTime.Now; _file.ContentType = file.ContentType; _file.FileName = file.FileName; _file.FileSize = file.ContentLength.ToString(); db.Files.Add(_file); db.SaveChanges(); fileId = _file.ID; } } if (!model.IsHaveFile) { if (model.FileID != 0) { Models.File _file = new Models.File(); _file = db.Files.Find(model.FileID); var path = Server.MapPath("~/Upload/" + _file.Path); System.IO.File.Delete(path); db.Files.Remove(_file); db.SaveChanges(); fileId = 0; } } ResourceLink link = new ResourceLink(); link = db.ResourceLinks.Find(model.ID); link.IsHaveFile = model.IsHaveFile; link.LinkTypeID = model.LinkTypeID; link.Title = model.Title; link.URL = model.URL; link.FileID = fileId; db.SaveChanges(); return RedirectToAction("LinkManager"); }
//DONT USE THIS IF YOU NEED TO ALLOW LARGE FILES UPLOADS //Credit to i-e-b and his ASP.Net uploader for the bulk of the upload helper methods - https://github.com/i-e-b/jQueryFileUpload.Net private void UploadPartialFile( string contentRange, HttpRequestBase request, List<ViewDataUploadFilesResult> statuses) { if (request.Files.Count != 1) throw new HttpRequestValidationException("Attempt to upload chunked file containing more than one fragment per request"); string[] ranges = contentRange.Split(new char[] { ' ', '-', '/' }); var upload = request.Files[0]; if (upload != null && upload.ContentLength > 0) { String fileName = System.IO.Path.GetFileName(upload.FileName); String contentType = upload.ContentType; Models.File currFile = null; using (var reader = new System.IO.BinaryReader(upload.InputStream)) { byte[] content = reader.ReadBytes(upload.ContentLength); if (ranges.Length>1 && ranges[1] == "0") { //this is first part => create new file; var avatar = new Models.File { FileName = fileName, FileType = FileType.Avatar, ContentType = contentType, Content = content }; currFile = fileService.addFile(avatar); } else { currFile = fileService.getFile(fileName); //append the file content byte[] newContent = new byte[currFile.Content.Length + content.Length]; Array.Copy(currFile.Content, newContent, currFile.Content.Length); Array.Copy(content, 0, newContent, currFile.Content.Length, content.Length); currFile.Content = newContent; fileService.saveFile(); } string imageUrl = "/File/Download?id=" + currFile.FileId; if (upload.ContentType.Contains("image")) { imageUrl = "/File?id=" + currFile.FileId; } statuses.Add(new ViewDataUploadFilesResult() { id = currFile.FileId, name = upload.FileName, size = currFile.Content.Length, type = upload.ContentType, url = imageUrl, delete_url = "/File/Delete?id=" + currFile.FileId, thumbnail_url = @"data:image/png;base64," + EncodeFile(currFile.Content), delete_type = "POST", }); } } }
//DONT USE THIS IF YOU NEED TO ALLOW LARGE FILES UPLOADS //Credit to i-e-b and his ASP.Net uploader for the bulk of the upload helper methods - https://github.com/i-e-b/jQueryFileUpload.Net private void UploadWholeFile(HttpRequestBase request, List<ViewDataUploadFilesResult> statuses) { for (int i = 0; i < request.Files.Count; i++) { var upload = request.Files[i]; if (upload != null && upload.ContentLength > 0) { String fileName = System.IO.Path.GetFileName(upload.FileName); String contentType = upload.ContentType; using (var reader = new System.IO.BinaryReader(upload.InputStream)) { var avatar = new Models.File { FileName = fileName, FileType = FileType.Avatar, ContentType = contentType, Content = reader.ReadBytes(upload.ContentLength) }; Models.File file = fileService.addFile(avatar); string imageUrl = "/File/Download?id=" + file.FileId; if (upload.ContentType.Contains("image")) { imageUrl = "/File?id=" + file.FileId; } statuses.Add(new ViewDataUploadFilesResult() { id = file.FileId, name = upload.FileName, size = upload.ContentLength, type = upload.ContentType, url = imageUrl, delete_url = "/File/Delete?id=" + file.FileId, thumbnail_url = @"data:image/png;base64," + EncodeFile(file.Content), delete_type = "POST", }); } } } }
public async void AsyncOperationScheduled(bool async) { // Arrange var shareFileClient = GetShareFileClient(true); ConfigureAsyncOperationScheduled(); var newItem = new Models.File { Parent = new Folder { Id = "fo" + GetId(34) } }; var query = shareFileClient.Items.Update(shareFileClient.Items.GetAlias("fi" + GetId(34)), newItem); // Act try { if (async) { await query.ExecuteAsync(); } else query.Execute(); } // Assert catch (AsyncOperationScheduledException asyncOperationScheduledException) { Assert.Pass(); return; } Assert.Fail(); }
private List<Models.File> parseFolder(string xml, string WorkSpace) { List<Models.File> files = new List<Models.File>(); XmlDocument xmlDoc = new XmlDocument(); xmlDoc.LoadXml(xml); XmlNodeList children = xmlDoc.GetElementsByTagName("tree").Item(0).ChildNodes; foreach (XmlNode child in children) { Models.File file = new Models.File(); file.WorkSpace = WorkSpace; System.Diagnostics.Debug.WriteLine("child:" + child.Name); //ignoring the pagination child if (child.Name.Equals("tree")) { foreach (XmlAttribute attribute in child.Attributes) { switch (attribute.Name) { case "text": file.Label = attribute.Value; break; case "is_file": file.Folder = attribute.Value.Equals("false"); break; case "filename": file.Id = attribute.Value; break; case "mimestring": file.Mime = attribute.Value; System.Diagnostics.Debug.WriteLine("MIME:" + file.Mime); break; } } files.Add(file); } } return files; }