private string UploadHotelImage(string Base64 = "", int Id = 0, string FileName = "") { string rs = ""; UploadFileResult UploadResult = null; if (Base64.StartsWith("data:image") && Base64.Contains(";base64,")) { string Url = string.Format(ConfigUtil.GetConfigurationValueFromKey("HotelImagesDerectory", false), Id); try { UploadResult = CommonUtil.UploadBase64File( Base64, FileName, Url, ImageFormat.Png, 20 ); } catch (Exception) { return(""); } if (UploadResult == null || UploadResult.HasError) { return(""); } else { return(UploadResult.FilePath); } } return(rs); }
public UploadFileResult UploadFile(HttpPostedFileBase file, string uploadFolderPath, bool onlyImages = false) { var upResult = new UploadFileResult { UploadSuccessful = true }; var fileName = Path.GetFileName(file.FileName); if (fileName != null) { upResult = FileChecks(file, upResult, fileName, onlyImages); if (!upResult.UploadSuccessful) { return(upResult); } // Sort the file name var newFileName = $"{AppHelpers.GenerateComb()}_{fileName.Trim(' ').Replace("_", "-").Replace(" ", "-").ToLower()}"; var path = Path.Combine(uploadFolderPath, newFileName); // Save the file to disk file.SaveAs(path); var hostingRoot = HostingEnvironment.MapPath("~/") ?? ""; var fileUrl = path.Substring(hostingRoot.Length).Replace('\\', '/').Insert(0, "/"); upResult.UploadedFileName = newFileName; upResult.UploadedFileUrl = fileUrl; } return(upResult); }
/// <summary> /// Upload a file to an Umbraco upload field /// </summary> /// <param name="file"></param> /// <param name="memberMediaFolderId"></param> /// <param name="onlyImages"></param> /// <returns></returns> public UploadFileResult UploadFile(HttpPostedFileBase file, int memberMediaFolderId, bool onlyImages = false) { var upResult = new UploadFileResult { UploadSuccessful = true }; var fileName = Path.GetFileName(file.FileName); if (fileName != null) { // check standard Dialogue stuff upResult = FileChecks(file, upResult, fileName, onlyImages); if (!upResult.UploadSuccessful) { return(upResult); } // Create the umbraco media file var ms = AppHelpers.UmbServices().MediaService; var media = ms.CreateMedia(fileName, memberMediaFolderId, "Image"); media.SetValue("umbracoFile", file); ms.Save(media); // Get this saved media out the cache var typedMedia = AppHelpers.UmbHelper().TypedMedia(media.Id); // Set the Urls upResult.UploadedFileName = typedMedia.Name; upResult.UploadedFileUrl = typedMedia.Url; upResult.MediaId = typedMedia.Id; } return(upResult); }
public ActionResult Edit(int id, int newsType, string title, string subHead, HttpPostedFileBase img, string content, int isshow, int priority) { ViewBag.Error = "none"; MldNews model = dal.Query(id); if (img != null && img.ContentLength > 0) { UploadFileResult result = img.FileUpLoad("img", 1024 * 1024 * 4, "images"); if (!result.Ok) { ViewBag.Error = result.Data; } else { model.Img = result.Data; } } model.NewsType = newsType; model.SubHead = subHead; model.Content = content; model.IsShow = isshow; model.Priority = priority; model.Title = title; if (dal.Update(model)) { ViewBag.Success = "ok"; } else { ViewBag.Error = "添加失败"; } return(View(model)); }
public ActionResult Index(int pid, HttpPostedFileBase img) { ViewBag.Error = "none"; string imgUrl = ""; if (img != null && img.ContentLength > 0) { UploadFileResult result = img.FileUpLoad("img", 1024 * 1024 * 4, "images"); if (!result.Ok) { ViewBag.Error = result.Data; } else { imgUrl = result.Data; MldProductImg model = new MldProductImg(); model.Img = imgUrl; model.Pid = pid; if (advDal.Add(model) > 0) { ViewBag.Success = "ok"; } else { ViewBag.Error = "Error"; } } } else { ViewBag.Error = "Please select the picture to upload"; } return(View()); }
public JsonResult UploadFile(HttpPostedFileBase Uploadfile, string PrefixInfo) { UploadFileResult result = CheckAndSaveUploadFile(Uploadfile, PrefixInfo); if (result.JsonReturnCode > 0) { if (sessionData.trading.UploadFiles.Any(x => x.Key == PrefixInfo)) { sessionData.trading.UploadFiles[PrefixInfo] = result.TempFileName; } else { sessionData.trading.UploadFiles.Add(PrefixInfo, result.TempFileName); } } else { //todo:need remove old file. if (sessionData.trading.UploadFiles.Any(x => x.Key == PrefixInfo)) { sessionData.trading.UploadFiles.Remove(PrefixInfo); } } return(Json(result, JsonRequestBehavior.DenyGet)); }
private UploadFileResult CheckAndSaveUploadFile(HttpPostedFileBase Uploadfile, string PreFix) { UploadFileResult result = new UploadFileResult() { }; if (Uploadfile != null) { try { string FileName = PreFix + DateTime.Now.ToString("yyyyMMddHHmmssf") + Path.GetExtension(Uploadfile.FileName); result.FileName = Uploadfile.FileName;//User's uploaded file name. result.FileType = Uploadfile.ContentType; result.FileSize = ConvertFileSize(Uploadfile.ContentLength, PreFix); result.TempFileName = "/UploadTemp/" + FileName;//Server given name. Uploadfile.SaveAs(GetTempPathFileName(FileName)); result.setMessage("Done"); } catch (Exception ex) { result.setException(ex, "CheckAndSaveUploadFile"); } } return(result); }
public async static Task <UploadFileResult> UploadVideo(IFormFile file, string containerName, string fileStart) { var fileName = fileStart + "-0"; var filetype = file.ContentType; while (await utility.BlobExistsOnCloud(containerName, fileName + "." + filetype)) { var ids = fileName.Split('-'); var lastDigit = int.Parse(ids.Last()); lastDigit += 1; fileName = fileStart + "-" + lastDigit; } fileName = fileName + "." + filetype; var imageStream = file.OpenReadStream(); var result = await utility.UploadBlob(fileName, containerName, imageStream); if (result != null) { var result = new UploadFileResult(result.Uri.ToString(), fileName); return(result.Uri.ToString()); } return(new UploadFileResult()); }
//TODO: move to repo public static UploadFileResult ToUploadPathResult(this HttpResponseMessage response) { var res = new UploadFileResult { HttpStatusCode = response.StatusCode, HasReturnedData = false }; if (response.IsSuccessStatusCode) { var strres = response.Content.ReadAsStringAsync().Result; if (string.IsNullOrEmpty(strres)) { return(res); } res.HasReturnedData = true; var resp = strres.Split(';'); res.Hash = new FileHashMrc(resp[0]); res.Size = resp.Length > 1 ? long.Parse(resp[1].Trim('\r', '\n', ' ')) : 0; } return(res); }
public ActionResult UploadFile(HttpPostedFileBase file) { try { using (MeuContexto contexto = new MeuContexto()) { if (file.ContentLength > 0) { UploadFileResult uploadFileResult = new UploadFileResult(); uploadFileResult.Nome = Path.GetFileName(file.FileName); uploadFileResult.Caminho = Path.Combine(Server.MapPath("~/UploadedFiles"), uploadFileResult.Nome); file.SaveAs(uploadFileResult.Caminho); uploadFileResult.CalculaHash(uploadFileResult.Caminho); ViewBag.Message = uploadFileResult.Hash; contexto.uploadFileResults.Add(uploadFileResult); contexto.SaveChanges(); } } return(View()); } catch { ViewBag.Message = "File upload failed!!"; return(View()); } }
/// <summary> /// Uploads a file from a posted file /// </summary> /// <param name="file"></param> /// <param name="uploadFolderPath"></param> /// <param name="localizationService"></param> /// <param name="onlyImages"></param> /// <returns></returns> public static UploadFileResult UploadFile(this HttpPostedFileBase file, string uploadFolderPath, ILocalizationService localizationService, bool onlyImages = false) { var upResult = new UploadFileResult { UploadSuccessful = true }; var storageProvider = StorageProvider.Current; var fileOkResult = file.CanBeUploaded(localizationService); if (fileOkResult.IsOk) { if (!Directory.Exists(uploadFolderPath)) { Directory.CreateDirectory(uploadFolderPath); } var fileName = fileOkResult.FileName; var fileExtension = fileOkResult.FileExtension; // Store these here as we may change the values within the image manipulation string newFileName; // See if this is an image, if so then do some extra checks if (fileOkResult.IsImage) { // Rotate image if wrong want around var sourceimage = file.ToImage(); // Change the extension to jpg as that's what we are saving it as fileName = fileName.Replace(fileExtension, ""); fileName = string.Concat(fileName, "jpg"); // Sort the file name newFileName = fileName.CreateFilename(); // Upload the image upResult = sourceimage.Upload(uploadFolderPath, newFileName); // Remove now sourceimage.Dispose(); } else { // Sort the file name newFileName = fileName.CreateFilename(); upResult.UploadedFileUrl = storageProvider.SaveAs(uploadFolderPath, newFileName, file); } upResult.UploadedFileName = newFileName; } else { upResult.UploadSuccessful = false; upResult.ErrorMessage = fileOkResult.Message; } return(upResult); }
public IHttpActionResult Update(RoomDetail Item) { ApiResult <RoomResult> rs = new ApiResult <RoomResult>(); if (Item == null) { rs.Failed(new ErrorObject { Code = "EXCEPTION", Description = "Đéo nhận dữ liệu truyền vào! 😒 " }); return(Content(HttpStatusCode.BadRequest, rs)); } if (!ModelState.IsValid) { // Lỗi validate dữ liệu trả ra từ model foreach (string key in ModelState.Keys) { ModelState current = ModelState[key]; foreach (ModelError error in current.Errors) { rs.Failed(new ErrorObject() { Code = key, Description = error.ErrorMessage }); } } return(Content(HttpStatusCode.BadRequest, rs)); } UploadFileResult uploadLogo = null; if (Item.Avatar.StartsWith("data:image")) { uploadLogo = CommonUtil.UploadBase64File( Item.Avatar, string.Format("{0}_{1}.png", Item.Name.Replace(" ", "_"), "Avatar"), ConfigUtil.GetConfigurationValueFromKey("RoomAvatarDerectory", false), ImageFormat.Png, 20 ); if (uploadLogo != null && !uploadLogo.HasError) { Item.Avatar = uploadLogo.FilePath; } } rs = roomDAL.Update(Item, UserInfo.Id); if (!rs.Succeeded) { return(Content(HttpStatusCode.BadRequest, rs)); } return(Ok(rs)); }
/// <summary> /// 上传附件 /// </summary> /// <returns></returns> public JsonResult UploadAttachment() { if (Request.Files == null || Request.Files.Count == 0) { return(Json(new { result = false, Message = "请选择要上传的文件!" }, JsonRequestBehavior.AllowGet)); } HttpPostedFileBase fileData = Request.Files[0]; UploadFileResult resultTemp = new UploadFileResult(); if (fileData != null) { try { int _limitedFileSize = 10000000; int.TryParse(ConfigurationManager.AppSettings["LimitedFileSize"], out _limitedFileSize); if (fileData.ContentLength > _limitedFileSize) { return(Json(new { result = false, Message = "上传的文件过大!" }, JsonRequestBehavior.AllowGet)); } // 文件上传后的保存路径 HttpContext context = System.Web.HttpContext.Current; string savePath = context.Server.MapPath("~"); string filePath = savePath + ConfigurationManager.AppSettings["UploadTmp"]; if (!Directory.Exists(filePath)) { Directory.CreateDirectory(filePath); } string fileName = Path.GetFileName(fileData.FileName); // 原始文件名称 string fileExtension = Path.GetExtension(fileName); // 文件扩展名 if (CommentHelper.IsAllowUploadFile(fileExtension)) { string saveName = Guid.NewGuid().ToString() + fileExtension; // TODO 保存文件名称 fileData.SaveAs(filePath + saveName); string baseDirectory = filePath.Substring(filePath.LastIndexOf('\\', filePath.Length - 2)).Trim('\\'); resultTemp.url = "/" + baseDirectory + saveName; //baseDirectory 以 /结尾 resultTemp.saveName = saveName; resultTemp.name = fileName; List <UploadFileResult> array = new List <UploadFileResult>(); array.Add(resultTemp); return(Json(new { result = true, files = array })); } else { return(Json(new { result = false, Message = "上传的文件类型不符合!" }, JsonRequestBehavior.AllowGet)); } } catch (Exception ex) { return(Json(new { result = false, Message = ex.Message }, JsonRequestBehavior.AllowGet)); } } else { return(Json(new { result = false, Message = "请选择要上传的文件!" }, JsonRequestBehavior.AllowGet)); } }
public IHttpActionResult SendImgMsgNew() { string userId = HttpContext.Current.Request.Form["userId"]; string touid = HttpContext.Current.Request.Form["touid"]; if (string.IsNullOrEmpty(userId)) { return(Json(new { Success = false, Content = "", Error = "userId为空", Message = "操作失败", Count = 0, Total = 0 })); } if (string.IsNullOrEmpty(touid)) { return(Json(new { Success = false, Content = "", Error = "touid为空", Message = "操作失败", Count = 0, Total = 0 })); } var fileList = System.Web.HttpContext.Current.Request.Files; if (fileList.Count == 0) { return(Json(new { Success = false, Content = "", Error = "文件读取失败", Message = "操作失败", Count = 0, Total = 0 })); } var file = new HttpPostedFileWrapper(fileList[0]) as HttpPostedFileBase; var uid = userId; string strPostfix = file.FileName.Substring(file.FileName.LastIndexOf(".") + 1); if (strPostfix.ToLower() != "gif" && strPostfix.ToLower() != "jpg" && strPostfix.ToLower() != "pic" && strPostfix.ToLower() != "bmp" && strPostfix.ToLower() != "jpeg" && strPostfix.ToLower() != "png") { return(Json(new { Success = false, Content = "", Error = "请上传图片格式" + "(bmp;jpg;jpeg;png;tif;pic;)", Message = "操作失败", Count = 0, Total = 0 })); } var result = FileService.Upload(file, "ZK-700"); if (result.Success) { //图片不需要转换 var fileCode = (string)result.Content; var fileuploadresult = new UploadFileResult(); fileuploadresult.fileCode = fileCode; fileuploadresult.convertID = 0; fileuploadresult.fileUrl = ConfigHelper.GetConfigString("OkcsServer") + "/imwebapi/Home/Download?title=" + file.FileName + "&fileCode=" + result.Content; return(Json(new { Success = true, Content = fileuploadresult, Error = "", Message = "操作成功", Count = 0, Total = 0 })); } return(Json(new { Success = false, Content = "", Error = result.Error, Message = "操作失败", Count = 0, Total = 0 })); }
private void uplAttachment_UploadFileCompleted(object sender, UploadCompletedEventArgs e) { UploadFileResult result = e.Result; txtAttachmentName.Text = result.Name; _planning.Attachment = System.IO.File.ReadAllBytes(result.TempFileFullName); _planning.AttachmentName = result.Name; System.IO.File.Delete(result.TempFileFullName); }
/// <summary> /// 上传题目 /// </summary> /// <returns></returns> private ResultMsg <UploadFileResult> UploadQuestionExcel() { ResultMsg <UploadFileResult> result = new ResultMsg <UploadFileResult>(); string moduleName = "Question"; UploadFileResult uploadFileResult = UploadFile.FileUpload(HttpContext.Current, moduleName).First(); result.data = uploadFileResult; return(result); }
public UploadFileResult UploadFile(string fileID, string fileName, byte[] data, bool isFirstChunk, bool isLastChunk, Dictionary <string, string> customParams) { UploadFileResult result = new UploadFileResult(); string extension = Path.GetExtension(fileName); string tempFileName = ""; string tempFilePath = ""; string tempUpFilePath = TempPathForUploadedFiles; if (!Directory.Exists(tempUpFilePath)) { Directory.CreateDirectory(tempUpFilePath); } if (isFirstChunk) { // 第一个文件块 ServiceLog.Log("大文件上传", "UploadFileService", fileName, "开始上传啦"); tempFileName = GetNewFileName(tempUpFilePath, extension) + "_temp"; tempFilePath = Path.Combine(tempUpFilePath, tempFileName); } else { // 非第一个文件块 tempFileName = fileID; tempFilePath = Path.Combine(tempUpFilePath, tempFileName); } // 临时文件名作为文件唯一标识 result.FileID = tempFileName; // 生成 SHA1 散列值 result.SHA1 = SecurityUtility.SHA1(data); // 写入数据 using (FileStream fs = File.Open(tempFilePath, FileMode.Append)) { fs.Write(data, 0, data.Length); fs.Flush(); fs.Close(); } if (isLastChunk) { // 保存上传文件 result.FileID = DealUploadedFile(fileName, tempFilePath, customParams); // 删除临时文件 if (File.Exists(tempFilePath)) { File.Delete(tempFilePath); } } return(result); }
public ActionResult Edit(int id, string name, HttpPostedFileBase homebg, HttpPostedFileBase icon, string subhead, string content, int homeshowflag) { ViewBag.Error = "none"; MldApplicationArea model = dal.Query(id); string imgUrl1 = model.HomeBg; if (homebg != null && homebg.ContentLength > 0) { UploadFileResult result = homebg.FileUpLoad("img", 1024 * 1024 * 4, "applicationarea"); if (!result.Ok) { ViewBag.Error = result.Data; } else { imgUrl1 = result.Data; } } string imgUrl2 = model.Icon; if (icon != null && icon.ContentLength > 0) { UploadFileResult result = icon.FileUpLoad("img", 1024 * 1024 * 4, "applicationarea"); if (!result.Ok) { ViewBag.Error = result.Data; } else { imgUrl2 = result.Data; } } model.Content = content; model.HomeBg = imgUrl1; model.Icon = imgUrl2; model.Name = name; model.SubHead = subhead; model.HomeShowFlag = homeshowflag; if (dal.Update(model)) { ViewBag.Success = "ok"; } else { ViewBag.Error = "Error"; } model = dal.Query(id); return(View(model)); }
public static UploadFileResult ToUploadPathResult(this string data) { var resp = data.Split(';'); var res = new UploadFileResult { Hash = resp[0], Size = resp.Length > 1 ? long.Parse(resp[1].Trim('\r', '\n', ' ')) : 0 }; return res; }
public IHttpActionResult SendFileMsgNew() { string userId = HttpContext.Current.Request.Form["userId"]; string touid = HttpContext.Current.Request.Form["touid"]; var fileList = System.Web.HttpContext.Current.Request.Files; if (string.IsNullOrEmpty(userId)) { return(Json(new { Success = false, Content = "", Error = "userId为空", Message = "操作失败", Count = 0, Total = 0 })); } if (string.IsNullOrEmpty(touid)) { return(Json(new { Success = false, Content = "", Error = "touid为空", Message = "操作失败", Count = 0, Total = 0 })); } if (fileList.Count == 0) { return(Json(new { Success = false, Content = "", Error = "文件读取失败", Message = "操作失败", Count = 0, Total = 0 })); } var file = new HttpPostedFileWrapper(fileList[0]) as HttpPostedFileBase; var result = FileService.Upload(file, "ZK-700"); if (result.Success) { var fileCode = (string)result.Content; string convertTaskId; var b = FileService.FileConvert(fileCode, out convertTaskId); var fileuploadresult = new UploadFileResult(); fileuploadresult.fileCode = fileCode; fileuploadresult.convertID = string.IsNullOrEmpty(convertTaskId) ? 0 : Convert.ToInt32(convertTaskId); fileuploadresult.fileUrl = ConfigHelper.GetConfigString("OkcsServer") + "/imwebapi/Home/Download?title=" + file.FileName + "&fileCode=" + result.Content; return(Json(new { Success = true, Content = fileuploadresult, Error = "", Message = "操作成功", Count = 0, Total = 0 })); } return(Json(new { Success = false, Content = "", Error = result.Error, Message = "操作失败", Count = 0, Total = 0 })); }
private static UploadFileResult FileChecks(HttpPostedFileBase file, UploadFileResult upResult, string fileName, bool onlyImages = false) { //Before we do anything, check file size if (file.ContentLength > Dialogue.Settings().FileUploadMaximumFilesize) { //File is too big upResult.UploadSuccessful = false; upResult.ErrorMessage = AppHelpers.Lang("Post.UploadFileTooBig"); return(upResult); } // now check allowed extensions var allowedFileExtensions = Dialogue.Settings().FileUploadAllowedExtensions; if (onlyImages) { allowedFileExtensions = new List <string> { "jpg", "jpeg", "png", "gif" }; } if (allowedFileExtensions.Any()) { // Get the file extension var fileExtension = Path.GetExtension(fileName.ToLower()); // If can't work out extension then just error if (string.IsNullOrEmpty(fileExtension)) { upResult.UploadSuccessful = false; upResult.ErrorMessage = AppHelpers.Lang("Errors.GenericMessage"); return(upResult); } // Remove the dot then check against the extensions in the web.config settings fileExtension = fileExtension.TrimStart('.'); if (!allowedFileExtensions.Contains(fileExtension)) { upResult.UploadSuccessful = false; upResult.ErrorMessage = AppHelpers.Lang("Post.UploadBannedFileExtension"); return(upResult); } } return(upResult); }
public static UploadFileResult Upload(this Image image, string uploadFolderPath, string fileName) { var extension = Path.GetExtension(fileName); fileName = Guid.NewGuid().ToString(); var upResult = new UploadFileResult { UploadSuccessful = true }; try { // Create directory if it doesn't exist if (!Directory.Exists(uploadFolderPath)) { Directory.CreateDirectory(uploadFolderPath); } // If no file name make one if (string.IsNullOrWhiteSpace(fileName)) { fileName = $"{fileName.ToLower()}.jpg"; } else { fileName = $"{fileName.ToLower()}{extension}"; } using (var stream = new MemoryStream()) { // Save the image as a Jpeg only var bmp = new Bitmap(image); bmp.Save(stream, ImageFormat.Jpeg); stream.Position = 0; var file = new MemoryFile(stream, "image/jpeg", fileName); // Get the storage provider and save file upResult.UploadedFileName = fileName; upResult.UploadedFileUrl = StorageProvider.Current.SaveAs(uploadFolderPath, fileName, file.InputStream); } } catch (Exception ex) { upResult.UploadSuccessful = false; upResult.ErrorMessage = ex.Message; } return(upResult); }
private UploadFileResult UploadAction(string targetDirPath) { AppContext.Logger.Debug($"EnterUploadAction"); var result = new UploadFileResult(); AppContext.Logger.Debug($"HttpContext.Current.Request.Files.Count:{HttpContext.Current.Request.Files.Count}"); if (HttpContext.Current.Request.Files.Count < 1) { result.errorMessage = "没有需要上传的文件"; return(result); } try { AppContext.Logger.Debug($"EnterUploadActionTry"); HttpPostedFile file = HttpContext.Current.Request.Files[0]; AppContext.Logger.Debug($"file.FileName:{file.FileName}"); if (string.IsNullOrEmpty(file.FileName)) { result.errorMessage = "没有需要上传的文件"; return(result); } if (file.ContentLength > _maxSizeLength) { result.errorMessage = "不允许上传超过 3M 的文件"; return(result); } var fileName = string.Concat(DateTime.Now.ToString("yyyyMMddHHmmssfff"), Path.GetExtension(file.FileName)); var targetDir = Path.Combine(AppContext.PathInfo.RootPath, targetDirPath); if (!Directory.Exists(targetDir)) { Directory.CreateDirectory(targetDir); } string targetPath = Path.Combine(targetDir, fileName); AppContext.Logger.Debug($"targetPath:{targetPath}"); file.SaveAs(targetPath); AppContext.Logger.Debug($"SaveAsEnd"); result.OriginalFileName = file.FileName; result.FileName = fileName; result.FileUrl = $"/{targetDirPath}/{fileName}"; result.success = true; } catch (Exception ex) { result.success = false; result.errorMessage = ex.Message; } return(result); }
public ActionResult Index(UploadFileResult model) { if (!ModelState.IsValid) { return(View(model)); } byte[] uploadedFile = new byte[model.File.InputStream.Length]; model.File.InputStream.Read(uploadedFile, 0, uploadedFile.Length); // now you could pass the byte array to your model and store wherever // you intended to store it return(Content("Thanks for uploading the file")); }
public async Task <IActionResult> Create(BooksCreateEditViewModel ViewModel) { if (ModelState.IsValid) { UploadFileResult result = new UploadFileResult(); string NewFileName = null; if (ViewModel.File != null) { NewFileName = _unitofwork.BooksRepository.CheckFileName(ViewModel.File.FileName); var path = $"{_environment.WebRootPath}/BookFiles/{NewFileName}"; result = await _unitofwork.BooksRepository.UploadFileAsync(ViewModel.File, path); } if (result.IsSuccess == true || result.IsSuccess == null) { ViewModel.FileName = NewFileName; if (await _unitofwork.BooksRepository.CreateBookAsync(ViewModel)) { return(RedirectToAction("Index")); } else { ViewBag.Error = "در انجام عملیات خطایی رخ داده است."; } } else { foreach (var item in result.Errors) { ModelState.AddModelError("", item); } } } ViewBag.LanguageID = new SelectList(_unitofwork.BaseRepository <Language>().FindAll(), "LanguageID", "LanguageName"); ViewBag.PublisherID = new SelectList(_unitofwork.BaseRepository <Publisher>().FindAll(), "PublisherID", "PublisherName"); ViewBag.AuthorID = new SelectList(_unitofwork.BaseRepository <Author>().FindAll().Select(t => new AuthorList { AuthorID = t.AuthorID, NameFamily = t.FirstName + " " + t.LastName }), "AuthorID", "NameFamily"); ViewBag.TranslatorID = new SelectList(_unitofwork.BaseRepository <Translator>().FindAll().Select(t => new TranslatorList { TranslatorID = t.TranslatorID, NameFamily = t.Name + " " + t.Family }), "TranslatorID", "NameFamily"); //ViewModel.SubCategoriesVM = new BooksSubcategoriesViewModel(_repository.GetAllCategories(), ViewModel.CategoryID); ViewModel.SubCategoriesVM = new BooksSubcategoriesViewModel(_unitofwork.BooksRepository.GetAllCategories(), ViewModel.CategoryID); return(View(ViewModel)); }
/// <summary> /// zakladni upload Photo na flickr s podporou retry pokusu (flickr je zrejme pretizeny a obcas haze service unavailable atd) /// </summary> public UploadFileResult UploadFile(File4Flickr file4Flickr, int maxRetryAttemps = 10) { var startTime = DateTime.Now; string photoId = null; var retryAttemp = 0; while (string.IsNullOrEmpty(photoId)) { try { photoId = UploadPicture(file4Flickr); // nechapu co to ma znamenat, ale jednou se ted stalo, ze upload probehl v poradku, avsak photoId bylo prazdne?? a na flickru fotky skutecne nejsou // vyvolam tedy vyjimku, aby probehlo uploadovani znovu if (string.IsNullOrEmpty(photoId)) { throw new FlickrExtenderException("PhotoId is empty!"); } } catch (Exception ex) when(ex is WebException || ex is IOException || ex is FlickrExtenderException) { // v pripade nekterych http protocol erroru zkusim retry - mozna by bylo vhodne to zkouset pri kazde chybe? if (retryAttemp++ < maxRetryAttemps) { if (ex is WebException) { Logger.Write(string.Format("WebException message:{0} status:{1}", ex.Message, (ex as WebException).Status), VtLogState.Error); } else { Logger.Write(string.Format("{0} error:{1}", ex.GetType().Name, ex.Message), VtLogState.Error); } Logger.Write(string.Format("Retry #:{0}", retryAttemp), VtLogState.Info); } else { throw; } } catch (FlickrApiException flickrApiException) { // doslo k nejake flickr API chybe (treba 5: Filetype was not recognised), takze nezkousim retry a skoncim upload s chybou var result = new UploadFileResult(file4Flickr, startTime, retryAttemp, flickrApiException); return(result); } } return(new UploadFileResult(file4Flickr, startTime, retryAttemp, photoId)); }
/// <summary> /// 上传文件 /// </summary> /// <param name="formFile"></param> /// <returns></returns> public ResultObject <UploadFileResult> Uploadfile(IFormFile formFile) { if (formFile == null || formFile.Length == 0) { return(new ResultObject <UploadFileResult>("文件不能为空")); } if (formFile.Length > _appSettings.Upload.LimitSize) { return(new ResultObject <UploadFileResult>("文件超过了最大限制")); } var ext = Path.GetExtension(formFile.FileName).ToLower(); if (!_appSettings.Upload.AllowExts.Contains(ext)) { return(new ResultObject <UploadFileResult>("文件类型不允许")); } //上传逻辑 var now = DateTime.Now; var yy = now.ToString("yyyy"); var mm = now.ToString("MM"); var dd = now.ToString("dd"); var fileName = Guid.NewGuid().ToString("n") + ext; var folder = Path.Combine(_appSettings.Upload.UploadPath, yy, mm, dd); if (!Directory.Exists(folder)) { Directory.CreateDirectory(folder); } var filePath = Path.Combine(folder, fileName); using (var fileStream = new FileStream(filePath, FileMode.Create, FileAccess.Write)) { formFile.CopyTo(fileStream); fileStream.Flush(true); } var fileUrl = $"{_appSettings.RootUrl}{_appSettings.Upload.RequestPath}/{yy}/{mm}/{dd}/{fileName}"; var response = new UploadFileResult { FileUrl = fileUrl }; return(new ResultObject <UploadFileResult>(response)); }
public UploadFileResult UploadFile(Image file, string uploadFolderPath) { var upResult = new UploadFileResult { UploadSuccessful = true }; var fileName = string.Concat(AppHelpers.GenerateComb(), ".jpg").ToLower(); // now check allowed extensions var allowedFileExtensions = Dialogue.Settings().FileUploadAllowedExtensions; if (allowedFileExtensions.Any()) { // Get the file extension var fileExtension = Path.GetExtension(fileName.ToLower()); // If can't work out extension then just error if (string.IsNullOrEmpty(fileExtension)) { upResult.UploadSuccessful = false; upResult.ErrorMessage = AppHelpers.Lang("Errors.GenericMessage"); return(upResult); } // Remove the dot then check against the extensions in the web.config settings fileExtension = fileExtension.TrimStart('.'); if (!allowedFileExtensions.Contains(fileExtension)) { upResult.UploadSuccessful = false; upResult.ErrorMessage = AppHelpers.Lang("Post.UploadBannedFileExtension"); return(upResult); } } // Sort the file name var path = Path.Combine(uploadFolderPath, fileName); // Save the file to disk file.Save(path, ImageFormat.Jpeg); var hostingRoot = HostingEnvironment.MapPath("~/") ?? ""; var fileUrl = path.Substring(hostingRoot.Length).Replace('\\', '/').Insert(0, "/"); upResult.UploadedFileName = fileName; upResult.UploadedFileUrl = fileUrl; return(upResult); }
public static async Task <UploadFileResult> UploadVideo(IFormFile file, string containerName, string fileStart) { var fileName = fileStart + "-0"; const string allowedFileTypes = "mp4 avi mpeg mov"; string fileType; var firstAlt = file.ContentType.Split('/').LastOrDefault(); if (allowedFileTypes.Contains(firstAlt)) { fileType = firstAlt; } else if (file.ContentType.Contains("quicktime")) { fileType = "mov"; } else { fileType = file.ContentType.Split('/').LastOrDefault() ?? "mp4"; } while (await utility.BlobExistsOnCloud(containerName, fileName + "." + fileType)) { var ids = fileName.Split('-'); var lastDigit = int.Parse(ids.Last()); lastDigit += 1; fileName = fileStart + "-" + lastDigit; } fileName = fileName + "." + fileType; var imageStream = file.OpenReadStream(); var result = await utility.UploadBlob(fileName, containerName, imageStream); if (result != null) { var response = new UploadFileResult(result.Uri.ToString(), fileName); return(response); } return(new UploadFileResult()); }
public ActionResult Edit(int id, string title, string subhead, int advType, string link, HttpPostedFileBase img, int isshow, int priority) { ViewBag.Error = "none"; string imgUrl = ""; if (img != null && img.ContentLength > 0) { UploadFileResult result = img.FileUpLoad("img", 1024 * 1024 * 4, "images"); if (!result.Ok) { ViewBag.Error = result.Data; } else { imgUrl = result.Data; } } MldAdv model = advDal.Query(id); model.AdvType = advType; model.Link = link; model.IsShow = isshow; model.Priority = priority; model.ID = id; model.SubHead = subhead; model.Title = title; if (!string.IsNullOrEmpty(imgUrl)) { model.Img = imgUrl; } if (advDal.Update(model)) { ViewBag.Success = "ok"; } else { ViewBag.Error = "Error"; } return(View(model)); }
public UploadFileResult UploadFile(UploadFile file) { UploadFileResult rst = new UploadFileResult(); try { string path; if (file.isUpdate) path = System.Environment.CurrentDirectory + "\\" + file.UpdateType + "\\" + file.FilePath; else path = file.FilePath; if (!Directory.Exists(path)) Directory.CreateDirectory(path); using (FileStream outputStream = new FileStream(path+"\\"+file.FileName, FileMode.OpenOrCreate, FileAccess.Write)) { file.FileStream.CopyTo(outputStream); outputStream.Flush(); } rst.IsSuccess = true; } catch(Exception e) { rst.IsSuccess = false; rst.Message = e.Message; } return rst; }