public ActionResult SaveUploadedFiles(int applicationId, int filenumber, int noOfFiles) { var UploadedFile = new CreateUploadApplicationFilesInput(); try { if (System.Web.HttpContext.Current.Request.Files.AllKeys.Any()) { var file = System.Web.HttpContext.Current.Request.Files["HelpSectionImages" + filenumber]; HttpPostedFileBase filebase = new HttpPostedFileWrapper(file); //var fileName = Path.GetFileName(filebase.FileName); //var path = Path.Combine(Server.MapPath("~/UploadedFiles/"), fileName); //filebase.SaveAs(path); using (var binaryReader = new BinaryReader(file.InputStream)) { UploadedFile.FileData = binaryReader.ReadBytes(file.ContentLength); } UploadedFile.applicationId = applicationId; UploadedFile.Type = file.ContentType; UploadedFile.FileName = file.FileName; UploadedFile.NoOfFiles = noOfFiles; _uploadApplicationFilesAppService.Create(UploadedFile); return(Json("File Saved Successfully.")); } else { return(Json("No File Saved.")); } } catch (Exception ex) { return(Json("Error While Saving.")); } }
public ActionResult SaveProfileImage() { try { if (System.Web.HttpContext.Current.Request.Files.AllKeys.Any()) { var pic = System.Web.HttpContext.Current.Request.Files["HelpSectionImages"]; HttpPostedFileBase filebase = new HttpPostedFileWrapper(pic); var fileName = Path.GetFileName(filebase.FileName); string fileExtension = Path.GetExtension(fileName); var path = string.Empty; if (fileExtension == ".xls" || fileExtension == ".xlsx") { //path = Path.Combine(Server.MapPath("~/TempImageUpload/"), DateTime.Now.ToString().Replace(' ', '_').Replace(':', '_').Replace('-', '_') + "_" + fileName); path = @"D:\RBSMEWEB\UploadFile\" + DateTime.Now.ToString().Replace(' ', '_').Replace(':', '_').Replace('-', '_').Replace('\\', '_').Replace('/', '_') + "_" + fileName; filebase.SaveAs(path); } else { return(Json("Wrong file format given")); } return(Json(path)); } else { return(Json("No File Saved.")); } } catch (Exception ex) { return(Json("Error While Saving.")); } }
public ActionResult Upload(HttpPostedFileWrapper file) { if (file == null) { var model = new ClientsIndexModel(); ViewBag.ImportApprovalStatusError = "Please select a file."; return(View("Index", model)); } var id = Guid.NewGuid(); string fileName = System.IO.Path.Combine(System.IO.Path.GetTempPath(), id.ToString()); var csvConf = new CsvHelper.Configuration.CsvConfiguration() { IsStrictMode = false, IsCaseSensitive = false, SkipEmptyRecords = true }; csvConf.ClassMapping <ApprovalStatusCsvMap>(); using (var csvReader = new CsvHelper.CsvReader(new System.IO.StreamReader(file.InputStream), csvConf)) { var updatedAt = DateTime.Now; var updatedBy = this.Permissions.User.Id; var csvChunkSize = 10000; var recordIndex = 1; Dictionary <int, int> fsas = new Dictionary <int, int>(); using (var db = new ccEntities()) { db.Imports.AddObject(new CC.Data.Import() { Id = id, StartedAt = DateTime.Now, UserId = this.Permissions.User.Id }); db.SaveChanges(); var q = (from fs in db.FundStatuses join a in db.ApprovalStatuses on fs.ApprovalStatusName equals a.Name select new { fsid = fs.Id, asid = a.Id } ); foreach (var intem in q) { fsas.Add(intem.fsid, intem.asid); } } foreach (var csvChunk in csvReader.GetRecords <ImportClient>().Split(csvChunkSize)) { string connectionString = System.Data.SqlClient.ConnectionStringHelper.GetProviderConnectionString(); using (var sqlBulk = new System.Data.SqlClient.SqlBulkCopy(connectionString, SqlBulkCopyOptions.KeepNulls)) { foreach (var record in csvChunk) { record.RowIndex = recordIndex++; record.ImportId = id; if (record.FundStatusId.HasValue && fsas.ContainsKey(record.FundStatusId.Value)) { record.ApprovalStatusId = fsas[record.FundStatusId.Value]; } record.UpdatedAt = updatedAt; record.UpdatedById = updatedBy; } var dataTable = csvChunk.ToDataTable(); var q = dataTable.Columns.OfType <System.Data.DataColumn>().Where(f => f.DataType == typeof(Int32)).Select(f => new { c = f.ColumnName, values = dataTable.Rows.OfType <System.Data.DataRow>().Select((r, i) => r[f.ColumnName]) }); sqlBulk.DestinationTableName = "ImportClients"; sqlBulk.NotifyAfter = 1000; sqlBulk.ColumnMappings.Add("ClientId", "ClientId"); sqlBulk.ColumnMappings.Add("FundStatusId", "FundStatusId"); sqlBulk.ColumnMappings.Add("RowIndex", "RowIndex"); sqlBulk.ColumnMappings.Add("ImportId", "ImportId"); sqlBulk.ColumnMappings.Add("UpdatedAt", "UpdatedAt"); sqlBulk.ColumnMappings.Add("UpdatedById", "UpdatedById"); sqlBulk.SqlRowsCopied += (s, e) => { System.Diagnostics.Debug.Write(e.RowsCopied); }; sqlBulk.WriteToServer(dataTable); } } } return(RedirectToAction("Preview", new { id = id })); }
public static void SetValue(this IContentBase content, string propertyTypeAlias, HttpPostedFileWrapper value) { SetValue(content, propertyTypeAlias, (HttpPostedFileBase)value); }
public WrappedJsonResult ImportFile(HttpPostedFileWrapper file, string optSmsTemplate) { JsonResponse json = new JsonResponse { Status = false }; try { if (file != null || file.ContentLength > 0) { int MaxContentLength = 1024 * 1024 * 3; //3 MB string[] AllowedFileExtensions = new string[] { ".csv" }; string fileExtension = System.IO.Path.GetExtension(file.FileName); if (!AllowedFileExtensions.Contains(fileExtension)) { json.Message = "Please select file of type : " + string.Join(", ", AllowedFileExtensions); } else if (file.ContentLength > MaxContentLength) { json.Message = "Maximum allowed file size is " + MaxContentLength + " bytes"; } else { string TempFolderPath = "~/Temp/"; string fileLocation = string.Format("{0}/{1}", Server.MapPath(TempFolderPath), file.FileName); if (System.IO.File.Exists(fileLocation)) { System.IO.File.Delete(fileLocation); } if (!Directory.Exists(Server.MapPath(TempFolderPath))) { Directory.CreateDirectory(Server.MapPath(TempFolderPath)); } file.SaveAs(fileLocation); // Load data DataTable data = new DataTable(); CSVReader csv = new CSVReader(); data = csv.GetDataTable(fileLocation, false); List <SMSModel> list = new List <SMSModel>(); foreach (DataRow r in data.Rows) { string sMessage = string.Empty; string sMsgErr = string.Empty; int number = 0; if (string.IsNullOrEmpty(r[0].ToString())) { sMsgErr += " หมายเลขโทรศัพท์ต้องไม่เป็นค่าว่าง"; } else if (!int.TryParse(r[0].ToString(), out number)) { sMsgErr += " หมายเลขโทรศัพท์ต้องเป็นตัวเลขเท่านั้น"; } else if (r[0].ToString().Length != 10) { sMsgErr += " หมายเลขโทรศัพท์ต้องเป็นตัวเลขจำนวน 10 หลัก เท่านั้น"; } try { sMessage = String.Format(optSmsTemplate, r.ItemArray); } catch { sMsgErr += " จำนวนพารามิเตอร์ {parameter} ในข้อความ ต้องมีจำนวนน้อยกว่าหรือเท่ากับจำนวนคอลัมน์ข้อมูลใน Excel"; } list.Add(new SMSModel { phonenumber = r[0].ToString(), message = sMessage, error = sMsgErr }); } if (System.IO.File.Exists(fileLocation)) { try { System.IO.File.Delete(fileLocation); } catch (System.IO.IOException e) { json.Message = "ERROR import excel file : " + e.Message; } } json.Data = list; json.Status = true; } } else { json.Message = "Plese select Excel File."; } } catch (Exception ex) { json = new JsonResponse { Status = false, Message = ex.Message, Total = 0 }; } json.Message = Shared.GetMsg(json.Status, json.Message); return(new WrappedJsonResult { Data = Json(json) }); }
/// <summary> /// 文件上传 /// </summary> /// <param name="postedFile">上传的文件对象</param> /// <param name="key">服务端配置索引名</param> /// <param name="fileInfor">文件上传后返回的信息对象</param> /// <returns></returns> public static FileMessage UploadFile(HttpPostedFile postedFile, string key, out FileInfor fileInfor) { HttpPostedFileBase obj = new HttpPostedFileWrapper(postedFile); return(UploadFile(obj, key, out fileInfor)); }
public virtual void SetPropertyValue(string propertyTypeAlias, HttpPostedFileWrapper value) { ContentExtensions.SetValue(this, propertyTypeAlias, value); }
public ActionResult Edit([Bind(Include = "ID_Documento,Nombre,ID_Clasificacion,Activo,Ruta_Documento")] DOCTOAYUDA dOCTOAYUDA, HttpPostedFileWrapper Ruta_Documento) { int pagina_id = 1507;//ID EN BASE DE DATOS FnCommon.ObtenerConfPage(db, pagina_id, User.Identity.Name, this.ControllerContext.Controller, 1500); string spras_id = ViewBag.spras_id; if (ModelState.IsValid) { DOCTOAYUDA actdOCTOAYUDA = db.DOCTOAYUDAs.Find(dOCTOAYUDA.ID_DOCUMENTO); if (Ruta_Documento != null)//Se ha seleccionado un nuevo archivo { if (!ExtensionesNS.Contains(Ruta_Documento.ContentType)) { if (Ruta_Documento.ContentLength < 31457280 && Ruta_Documento.ContentLength > 0)//30 MB maximo { //Elimina el anterior var eliminar = Path.Combine( Server.MapPath("~/Archivos/DoctosAyuda"), actdOCTOAYUDA.RUTA_DOCUMENTO.Split('/').Last()); FileInfo file = new FileInfo(eliminar); file.Delete(); //Guarda el nuevo archivo var fileName = Path.GetFileName(Ruta_Documento.FileName); dOCTOAYUDA.RUTA_DOCUMENTO = Path.Combine( Server.MapPath("~/Archivos/DoctosAyuda"), dOCTOAYUDA.ID_DOCUMENTO + "_" + fileName); Ruta_Documento.SaveAs(dOCTOAYUDA.RUTA_DOCUMENTO); actdOCTOAYUDA.RUTA_DOCUMENTO = "Archivos/DoctosAyuda/" + dOCTOAYUDA.ID_DOCUMENTO + "_" + Ruta_Documento.FileName; actdOCTOAYUDA.NOMBRE = dOCTOAYUDA.NOMBRE; actdOCTOAYUDA.ACTIVO = dOCTOAYUDA.ACTIVO; db.SaveChanges(); return(RedirectToAction("Index")); } else { TempData["Filesize"] = "El archivo excede el tamaño máximo permitido"; } } else { TempData["Extension"] = "No se admiten archivos con el tipo de extensión seleccionado."; } } else//No se actualiza el archivo, solo los demas campos { actdOCTOAYUDA.NOMBRE = dOCTOAYUDA.NOMBRE; actdOCTOAYUDA.ACTIVO = dOCTOAYUDA.ACTIVO; db.SaveChanges(); return(RedirectToAction("Index")); } } return(View(dOCTOAYUDA)); }
public njAsyncFile(HttpPostedFileWrapper postedfile) { Files = new List <Models.njAsyncFileUpload>(); this.AddItem(postedfile); }
public void ProcessRequest(HttpContext context) { if (context.Session["AccountId"] == null) { //context.Response.Write(new JObject(new JProperty("Status", 0), new JProperty("ErrorReason", "Session expired."))); HttpContext.Current.Response.StatusCode = 401; return; } HttpPostedFile postedfile = default(HttpPostedFile); try { postedfile = context.Request.Files[0]; string filename = postedfile.FileName.Substring(0, postedfile.FileName.LastIndexOf(".")); Press3.UserDefinedClasses.Validator validateObject = new Press3.UserDefinedClasses.Validator(); string ValidateResponse = ""; if (!ValidateFileName(filename)) { jObj = new JObject(new JProperty("Status", 0), new JProperty("ErrorReason", "File name should not contain i) Morethan one dot ii)Comma.")); context.Response.Write(jObj); return; } ValidateResponse = validateObject.TextValidate(filename, "PLAINTEXT"); if (ValidateResponse.ToString().ToUpper() != "OK") { jObj = new JObject(new JProperty("Status", 0), new JProperty("ErrorReason", "Invalid Characters Found In File Name Field")); context.Response.Write(jObj); return; } if (Path.GetExtension(postedfile.FileName).ToLower() != ".mp3" && Path.GetExtension(postedfile.FileName).ToLower() != ".wav") { jObj = new JObject(new JProperty("Status", 0), new JProperty("ErrorReason", "Invalid file extension,Please upload mp3 or wav file.")); context.Response.Write(jObj); return; } if (!(postedfile.ContentType == "audio/mpeg") && postedfile.ContentType == "audio/x-wav" && postedfile.ContentType == "audio/mpeg3" && postedfile.ContentType == "audio/wav" && postedfile.ContentType == "audio/x-pn-wav") { jObj = new JObject(new JProperty("Status", 0), new JProperty("ErrorReason", "Invalid file, Please check once.")); context.Response.Write(jObj); return; } string fileName = null; HttpPostedFileBase filebase = new HttpPostedFileWrapper(postedfile); byte[] buffer = new byte[512]; filebase.InputStream.Read(buffer, 0, 512); string content = System.Text.Encoding.UTF8.GetString(buffer); //if (Regex.IsMatch(content, "<|><script|<html|<head|<title|<body|<pre|<table|<a\\s+href|<img|<plaintext|<cross\\-domain\\-policy", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.Multiline)) //{ // jObj = new JObject(new JProperty("Status", 0), new JProperty("ErrorReason", "Uploaded file contains Invalid data, please check once.")); // context.Response.Write(jObj); // return; //} if (HttpContext.Current.Request.Browser.Browser.ToUpper() == "IE") { string[] files = postedfile.FileName.Split(new char[] { '\\' }); fileName = files[files.Length - 1]; } else { fileName = postedfile.FileName; } fileName = Regex.Replace(fileName, "[^A-Za-z0-9_.]", ""); string voice_ext = fileName.Substring(fileName.IndexOf("."), (fileName.Length - fileName.IndexOf("."))).ToLower(); string voice_clip_name = fileName.Substring(0, fileName.LastIndexOf(".")); string TimeSpan = DateTime.Now.ToString("ddhhmmss"); string spath = null; string patha = null; spath = context.Server.MapPath("~/VoiceClips/"); patha = spath + voice_clip_name + "_" + TimeSpan + voice_ext; postedfile.SaveAs(patha); try { object clip = ""; string fileNameWithPath = null; if ((System.IO.File.Exists(spath + voice_clip_name + "_" + TimeSpan + ".mp3"))) { fileNameWithPath = spath + voice_clip_name + "_" + TimeSpan + ".mp3"; clip = fileNameWithPath.Substring((fileNameWithPath.LastIndexOf("\\") + 1), fileNameWithPath.Length - (fileNameWithPath.LastIndexOf("\\") + 1)); jObj = new JObject(new JProperty("Status", 1), new JProperty("Clip", clip.ToString())); } else if ((System.IO.File.Exists(spath + voice_clip_name + "_" + TimeSpan + ".wav"))) { fileNameWithPath = spath + voice_clip_name + "_" + TimeSpan + ".wav"; clip = fileNameWithPath.Substring((fileNameWithPath.LastIndexOf("\\") + 1), fileNameWithPath.Length - (fileNameWithPath.LastIndexOf("\\") + 1)); jObj = new JObject(new JProperty("Status", 1), new JProperty("Clip", clip.ToString())); } else { jObj = new JObject(new JProperty("Status", 0), new JProperty("ErrorReason", "Something went wrong with the server.")); } context.Response.Write(jObj); } catch (Exception ex) { Logger.Error(ex.ToString()); jObj = new JObject(new JProperty("Status", 0), new JProperty("ErrorReason", "Something went wrong with the server.")); context.Response.Write(jObj); } } catch (Exception ex) { Logger.Error(ex.ToString()); jObj = new JObject(new JProperty("Status", 0), new JProperty("ErrorReason", "Something went wrong with the server.")); context.Response.Write(jObj); } }
public WrappedJsonResult _ImageUploadForm(FormCollection myForm, HttpPostedFileWrapper imageFile) { if (imageFile == null || imageFile.ContentLength == 0) { return(new WrappedJsonResult { Data = new { IsValid = false, Message = "No file was uploaded.", ImagePath = string.Empty } }); } //------------------------------------My Stuff---------------------------------// CImage myUploadImage = new CImage(); myUploadImage.title = myForm["title"]; myUploadImage.description = myForm["description"]; myUploadImage.createdDate = DateTime.Today; myUploadImage.type = 1;//(int)CImage.ImageType.Event; myUploadImage.userName = "******"; myUploadImage.createdDate = DateTime.Now; myUploadImage.imageMimeType = imageFile.ContentType; myUploadImage.imageFile = new byte[imageFile.ContentLength]; imageFile.InputStream.Read(myUploadImage.imageFile, 0, imageFile.ContentLength); try { context.Add <CImage>(myUploadImage); context.SaveChanges(); } catch (DbEntityValidationException e) { foreach (var eve in e.EntityValidationErrors) { //Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:", //eve.Entry.Entity.GetType().Name, eve.Entry.State); foreach (var ve in eve.ValidationErrors) { //Console.WriteLine("- Property: \"{0}\", Error: \"{1}\"", //ve.PropertyName, ve.ErrorMessage); ModelState.AddModelError(ve.PropertyName, ve.ErrorMessage); } } } //-------------------------------------------My Stuff ends-------------------------------------------// if (!ModelState.IsValid) { var myResult = new WrappedJsonResult { Data = new { IsValid = false, Message = RenderPartialViewToString("_ImageUploadForm", myUploadImage), ImagePath = "" } }; return(myResult); } var fileName = String.Format("{0}.jpg", Guid.NewGuid().ToString()); /*var imagePath = Path.Combine(Server.MapPath(Url.Content("~/Uploads")), fileName); * * imageFile.SaveAs(imagePath);*/ return(new WrappedJsonResult { Data = new { IsValid = true, Message = "", ImagePath = Url.Content(String.Format("~/Uploads/{0}", fileName)) } }); }
private Intranet.File SaveUpload(HttpPostedFileWrapper upload, ref int id_folder) { string uploadPath = Intranet.Properties.Settings.Default.UploadPath; Intranet.File dbfile = null; if (upload != null) { int id_user = Int32.Parse(User.Identity.GetUserId()); Folder folder; if (id_folder == 0) { folder = GetUserRootFolder(id_user); id_folder = folder.id_folder; } else { int tmp_id_folder = id_folder; folder = data.Folders.SingleOrDefault(f => f.id_folder == tmp_id_folder && f.id_user == id_user); } data.Database.Connection.Open(); var rnd = new Random(); int newid = rnd.Next(1000000000); dbfile = new Intranet.File { id_file = newid, id_user = id_user, id_folder = folder.id_folder, filename = "?", fileext = Path.GetExtension(upload.FileName), filesize = 0, height = 0, width = 0, image = false, name = upload.FileName, upload_date = DateTime.Now }; while (data.Files.Any(f => f.id_file == newid)) { newid = rnd.Next(1000000000); } data.Database.ExecuteSqlCommand("SET IDENTITY_INSERT [dbo].[Files] ON"); data.Files.Add(dbfile); data.SaveChanges(); data.Database.ExecuteSqlCommand("SET IDENTITY_INSERT [dbo].[Files] OFF"); string path = System.IO.Path.Combine(uploadPath, dbfile.id_file.ToString() + dbfile.fileext); upload.SaveAs(path); var finfo = new System.IO.FileInfo(path); dbfile.filesize = (int)finfo.Length; dbfile.filename = dbfile.id_file.ToString() + dbfile.fileext; try { Image image = Image.FromFile(path); dbfile.image = true; dbfile.width = image.Width; dbfile.height = image.Height; image.Dispose(); } catch { } data.SaveChanges(); } return(dbfile); }
public ActionResult create(String name, String mailaddress, String password, String passwordConfirmation, HttpPostedFileWrapper imagePath) { if (password != "" && passwordConfirmation != "") //空文字で登録できないようにする { if (password == passwordConfirmation) //パスワードと確認用パスワードの一致 { Teacher teacher = new Teacher(); teacher.name = name; teacher.mailaddress = mailaddress; teacher.setPassword(password); //パスワードダイジェスト化 if (imagePath != null) { imagePath.SaveAs(Server.MapPath(@"/uproadFiles/") + Path.GetFileName(imagePath.FileName)); teacher.profileImage = Path.GetFileName(imagePath.FileName); } teacher.language = DBNull.Value.ToString(); teacher.intoroduction = DBNull.Value.ToString(); teacher.address = DBNull.Value.ToString(); teacher.nationality = DBNull.Value.ToString(); if (teacher.create()) { Teacher.login(mailaddress, password); return(View("/Views/Teachers/Homes/mypage.cshtml", Teacher.currentUser())); } else { ViewBag.ErrorMessage = "登録済みのメールアドレスです。"; return(View("/Views/Teachers/Registrations/create.cshtml")); } } ViewBag.ErrorMessage = "パスワードと確認用パスワードが一致しませんでした。"; return(View("/Views/Teachers/Registrations/create.cshtml")); } ViewBag.ErrorMessage = "必須項目を入力してください。"; return(View("/Views/Teachers/Registrations/create.cshtml")); }
public string Put(int id) { try { NameValueCollection nvc = HttpContext.Current.Request.Form; string ID = nvc["Part_Type_ID"]; string what = nvc["blueprints"]; JArray bb = JArray.Parse(what); int k = 0; //Check if any blueprints should be removed foreach (JObject blueprint in bb) { bool flag = (bool)blueprint["Removed"]; if (flag == true) { int b_ID = (int)blueprint["Blueprint_ID"]; string File_Type = (string)blueprint["File_Type"]; //Delete from db db.Part_Blueprint.RemoveRange(db.Part_Blueprint.Where(x => x.Blueprint_ID == b_ID)); //Delete physical file string newName = "Blueprint_" + b_ID + "_" + "PartType_" + ID + File_Type; string completePath = HttpContext.Current.Server.MapPath("~/Files/") + newName; if (System.IO.File.Exists(completePath)) { System.IO.File.Delete(completePath); } k++; } } int key = db.Part_Blueprint.Count() == 0 ? 1 : (from t in db.Part_Blueprint orderby t.Blueprint_ID descending select t.Blueprint_ID).First() + 1; for (int i = 0; i < HttpContext.Current.Request.Files.Count; i++) { HttpPostedFileBase file = new HttpPostedFileWrapper(HttpContext.Current.Request.Files[i]); //Uploaded file //Use the following properties to get file's name, size and MIMEType int fileSize = file.ContentLength; string fileName = file.FileName; string mimeType = file.ContentType; System.IO.Stream fileContent = file.InputStream; Model.Part_Blueprint pb = new Part_Blueprint(); string newName = "Blueprint_" + key + "_" + "PartType_" + ID + GetDefaultExtension(mimeType); pb.Blueprint_ID = key; pb.File_Type = GetDefaultExtension(mimeType); pb.Name = fileName; pb.Part_Type_ID = Convert.ToInt32(ID); pb.location = "/Files/"; db.Part_Blueprint.Add(pb); //To save file, use SaveAs method file.SaveAs(HttpContext.Current.Server.MapPath("~/Files/") + newName); //File will be saved in application root key++; } db.SaveChanges(); return("true|Uploaded " + HttpContext.Current.Request.Files.Count + " files for part Type ID: " + ID + " and deleted " + k); } catch (DbEntityValidationException dbEx) { // Retrieve the error messages as a list of strings. var errorMessages = dbEx.EntityValidationErrors .SelectMany(x => x.ValidationErrors) .Select(x => x.ErrorMessage); // Join the list to a single string. var fullErrorMessage = string.Join("; ", errorMessages); // Combine the original exception message with the new one. var exceptionMessage = string.Concat(dbEx.Message, " The validation errors are: ", fullErrorMessage); return("false|Could not upload the files.|" + exceptionMessage); } catch (Exception ex) { return("false|Could not upload the files.|" + ex.ToString()); } }
public string Upload() { try { NameValueCollection nvc = HttpContext.Current.Request.Form; string ID = nvc["Part_Type_ID"]; int key = db.Part_Blueprint.Count() == 0 ? 1 : (from t in db.Part_Blueprint orderby t.Blueprint_ID descending select t.Blueprint_ID).First() + 1; for (int i = 0; i < HttpContext.Current.Request.Files.Count; i++) { HttpPostedFileBase file = new HttpPostedFileWrapper(HttpContext.Current.Request.Files[i]); //Uploaded file //Use the following properties to get file's name, size and MIMEType int fileSize = file.ContentLength; string fileName = file.FileName; string mimeType = file.ContentType; System.IO.Stream fileContent = file.InputStream; Model.Part_Blueprint pb = new Part_Blueprint(); string newName = "Blueprint_" + key + "_" + "PartType_" + ID + GetDefaultExtension(mimeType); pb.Blueprint_ID = key; pb.File_Type = GetDefaultExtension(mimeType); pb.Name = fileName; pb.Part_Type_ID = Convert.ToInt32(ID); pb.location = "/Files/"; db.Part_Blueprint.Add(pb); //To save file, use SaveAs method file.SaveAs(HttpContext.Current.Server.MapPath("~/Files/") + newName); //File will be saved in application root key++; } db.SaveChanges(); return("true|Uploaded " + HttpContext.Current.Request.Files.Count + " files for part Type ID: " + ID); } catch (DbEntityValidationException dbEx) { // Retrieve the error messages as a list of strings. var errorMessages = dbEx.EntityValidationErrors .SelectMany(x => x.ValidationErrors) .Select(x => x.ErrorMessage); // Join the list to a single string. var fullErrorMessage = string.Join("; ", errorMessages); // Combine the original exception message with the new one. var exceptionMessage = string.Concat(dbEx.Message, " The validation errors are: ", fullErrorMessage); return("false|Could not upload the files.|" + exceptionMessage); } catch (Exception ex) { return("false|Could not upload the files.|" + ex.ToString()); } }
public JsonResult JEditApplication(ApplicationViewModel oApplicationViewModel) { Response oResponseResult = null; string sRealFileName = string.Empty; string sModifiedFileName = string.Empty; HttpPostedFileBase filebase = null; var oFile = System.Web.HttpContext.Current.Request.Files["ApplicationLogoFile"]; if (oFile != null) { filebase = new HttpPostedFileWrapper(oFile); if (filebase.ContentLength > 0) { sRealFileName = filebase.FileName; sModifiedFileName = CommonHelper.AppendTimeStamp(filebase.FileName); } } oApplicationViewModel.APPLICATION_EXPIRY_DATE = DateTime.ParseExact(oApplicationViewModel.FORMATTED_EXPIRY_DATE, "d/M/yyyy", CultureInfo.InvariantCulture); oApplicationViewModel.APPLICATION_LOGO_PATH = sModifiedFileName; oApplicationViewModel.MODIFIED_BY = Convert.ToInt32(CurrentUser.nUserID); oResponseResult = this.oIApplicationService.oUpdateApplication(oApplicationViewModel); this.OperationResult = oResponseResult.OperationResult; switch (this.OperationResult) { case enumOperationResult.Success: { this.OperationResultMessages = CommonResx.MessageAddSuccess; if (oFile != null) { byte[] fileData = null; using (var binaryReader = new BinaryReader(filebase.InputStream)) { fileData = binaryReader.ReadBytes(filebase.ContentLength); } //MagickImage oMagickImage = new MagickImage(filebase.InputStream); //oMagickImage.Format = MagickFormat.Icon; //oMagickImage.Resize(72, 0); FileAccessService oFileAccessService = new FileAccessService(CommonHelper.sGetConfigKeyValue(ConstantNames.FileAccessURL)); //DirectoryPath = Saved Application ID string sDirectoryPath = oApplicationViewModel.ID.ToString(); string sFullFilePath = Path.Combine(sDirectoryPath, sModifiedFileName); oFileAccessService.CreateDirectory(sDirectoryPath); oFileAccessService.WirteFileByte(sFullFilePath, fileData); } this.OperationResult = enumOperationResult.Success; } break; case enumOperationResult.Faild: this.OperationResultMessages = CommonResx.MessageAddFailed; break; } return(Json( new { nResult = this.OperationResult, sResultMessages = this.OperationResultMessages }, JsonRequestBehavior.AllowGet)); }
private async Task <HttpResponseMessage> ProcessChunk(string filename, string directoryname, int chunknumber, int numberofChunks) { // Check if the request contains multipart/form-data. if (!Request.Content.IsMimeMultipartContent()) { throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType); } // Check that we are not trying to upload a file greater than 50MB Int32 maxinputlength = 51 * 1024 * 1024; if (Convert.ToInt32(HttpContext.Current.Request.InputStream.Length) > maxinputlength) { return(Request.CreateErrorResponse(HttpStatusCode.RequestEntityTooLarge, "Maximum upload chunk size exceeded")); } try { byte[] filedata = null; // If we have the custome header then we are processing hand made multipart-form-data if (HttpContext.Current.Request.Headers["CelerFT-Encoded"] != null) { // Read in the request HttpPostedFileBase base64file = new HttpPostedFileWrapper(HttpContext.Current.Request.Files["Slice"]); if (base64file == null) { return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, "No file chunk uploaded")); } // Convert the base64 string into a byte array byte[] base64filedata = new byte[base64file.InputStream.Length]; await base64file.InputStream.ReadAsync(base64filedata, 0, Convert.ToInt32(HttpContext.Current.Request.InputStream.Length)); var base64string = System.Text.UTF8Encoding.UTF8.GetString(base64filedata); filedata = Convert.FromBase64String(base64string); } else { HttpPostedFileBase file = new HttpPostedFileWrapper(HttpContext.Current.Request.Files["Slice"]); if (file == null) { return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, "No file chunk uploaded")); } filedata = new byte[file.InputStream.Length]; await file.InputStream.ReadAsync(filedata, 0, Convert.ToInt32(HttpContext.Current.Request.InputStream.Length)); } if (filedata == null) { return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, "No file chunk uploaded")); } // Write the byte array to a file var newfilename = filename.Split('.'); string baseFilename = Path.GetFileNameWithoutExtension(filename); string extension = Path.GetExtension(filename); string tempdirectoryname = Path.GetFileNameWithoutExtension(filename); var localFilePath = getFileFolder(directoryname + "\\" + tempdirectoryname) + "\\" + baseFilename + "." + chunknumber.ToString().PadLeft(16, Convert.ToChar("0")) + "." + extension + ".tmp"; var input = new MemoryStream(filedata); var outputFile = File.Open(localFilePath, FileMode.OpenOrCreate, FileAccess.Write, FileShare.Read); await input.CopyToAsync(outputFile); input.Close(); outputFile.Close(); filedata = null; return(new HttpResponseMessage() { Content = new StringContent(localFilePath), StatusCode = HttpStatusCode.OK }); } catch (Exception ex) { return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex)); } }
public ActionResult Register([Bind(Include = "Name,Surname,Email,Password")] Author author, HttpPostedFileWrapper file) { if (ModelState.IsValid) { _accountService.Register(author, file); return(RedirectToAction("Login")); } return(View(author)); }
public ActionResult Create([Bind(Include = "ID_Documento,Nombre,ID_Clasificacion,Activo,Ruta_Documento")] DOCTOAYUDA dOCTOAYUDA, HttpPostedFileWrapper Ruta_Documento) { int pagina_id = 1506;//ID EN BASE DE DATOS FnCommon.ObtenerConfPage(db, pagina_id, User.Identity.Name, this.ControllerContext.Controller, 1500); string spras_id = ViewBag.spras_id; ViewBag.ID_Clasificacion = new SelectList(db.DOCTOCLASIFTs.Where(t => t.SPRAS_ID == spras_id), "ID_Clasificacion", "Texto"); if (ModelState.IsValid) { if (!ExtensionesNS.Contains(Ruta_Documento.ContentType)) { if (Ruta_Documento.ContentLength < 31457280 && Ruta_Documento.ContentLength > 0)//30 MB { dOCTOAYUDA.ID_DOCUMENTO = getID_Docto(dOCTOAYUDA.ID_CLASIFICACION); var fileName = Path.GetFileName(Ruta_Documento.FileName); dOCTOAYUDA.RUTA_DOCUMENTO = Path.Combine( Server.MapPath("~/Archivos/DoctosAyuda"), dOCTOAYUDA.ID_DOCUMENTO + "_" + fileName); Ruta_Documento.SaveAs(dOCTOAYUDA.RUTA_DOCUMENTO); dOCTOAYUDA.RUTA_DOCUMENTO = "Archivos/DoctosAyuda/" + dOCTOAYUDA.ID_DOCUMENTO + "_" + Ruta_Documento.FileName; db.DOCTOAYUDAs.Add(dOCTOAYUDA); db.SaveChanges(); return(RedirectToAction("Index")); } else { TempData["Filesize"] = "El archivo excede el tamaño máximo permitido"; } } else { TempData["Extension"] = "No se admiten archivos con el tipo de extensión seleccionado."; } } dOCTOAYUDA.RUTA_DOCUMENTO = null; return(View(dOCTOAYUDA)); }
public ActionResult Create([Bind(Include = "Title,Description,Text,AuthorID,CategoryID")] Article article, HttpPostedFileWrapper file) { var email = (string)Session["AUTHOR"]; var author = _accountService.GetAuthorDashboard(email).Author; var list = _accountService.GetCategoryList().Categories; try { if (ModelState.IsValid) { _accountService.CreateNewBlogArticle(article, file); return(RedirectToAction("Dashboard")); } } catch (DbEntityValidationException e) { foreach (var eve in e.EntityValidationErrors) { Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:", eve.Entry.Entity.GetType().Name, eve.Entry.State); foreach (var ve in eve.ValidationErrors) { Console.WriteLine("- Property: \"{0}\", Error: \"{1}\"", ve.PropertyName, ve.ErrorMessage); } } throw; } var model = new NewBlogArticleViewModel { Author = author, Categories = list }; return(View(model)); }
public JsonResult JSaveEvent(EventViewModel oEventViewModel) { oEventViewModel.EVENT_DESCRIPTION = oEventViewModel.EVENT_DESCRIPTION.Replace(Environment.NewLine, "</br>"); Response oResponseResult = null; string sRealFileName = string.Empty; string sModifiedFileName = string.Empty; HttpPostedFileBase filebase = null; var oFile = System.Web.HttpContext.Current.Request.Files["EventImage"]; if (oFile != null) { filebase = new HttpPostedFileWrapper(oFile); if (filebase.ContentLength > 0) { sRealFileName = filebase.FileName; sModifiedFileName = CommonHelper.AppendTimeStamp(filebase.FileName); oEventViewModel.EVENT_IMG_FILE_PATH = Path.Combine(this.CurrentApplicationID.ToString(), "Events", sModifiedFileName).Replace('\\', '/'); } } oEventViewModel.EVENT_DATE = DateTime.ParseExact(string.Format("{0} {1}", oEventViewModel.FORMATTED_EVENT_DATE, oEventViewModel.EVENT_TIME), "dd/MM/yyyy HH:mm", CultureInfo.InvariantCulture); oEventViewModel.CREATED_BY = Convert.ToInt32(CurrentUser.nUserID); oEventViewModel.APPLICATION_ID = CurrentApplicationID; oEventViewModel.LANGUAGE_ID = Convert.ToInt32(this.CurrentApplicationLanguage); oResponseResult = this.oIEventService.oInsertEvent(oEventViewModel); this.OperationResult = oResponseResult.OperationResult; switch (this.OperationResult) { case enumOperationResult.Success: if (oFile != null) { FileAccessService oFileAccessService = new FileAccessService(CommonHelper.sGetConfigKeyValue(ConstantNames.FileAccessURL)); try { //DirectoryPath = Saved Application ID + Evemts Folder string sDirectoryPath = Path.Combine(this.CurrentApplicationID.ToString(), "Events"); string sFullFilePath = Path.Combine(sDirectoryPath, sModifiedFileName); oFileAccessService.CreateDirectory(sDirectoryPath); MagickImage oMagickImage = new MagickImage(filebase.InputStream); oMagickImage.Format = MagickFormat.Png; oMagickImage.Resize(Convert.ToInt32(CommonHelper.sGetConfigKeyValue(ConstantNames.ImageWidth)), Convert.ToInt32(CommonHelper.sGetConfigKeyValue(ConstantNames.ImageHeight))); oFileAccessService.WirteFileByte(sFullFilePath, oMagickImage.ToByteArray()); } catch (Exception ex) { Elmah.ErrorLog.GetDefault(System.Web.HttpContext.Current).Log(new Elmah.Error(ex)); } } if (oEventViewModel.IS_NOTIFY_USER && oEventViewModel.IS_ACTIVE) { string sEventName = oEventViewModel.EVENT_NAME; string sEventDesc = oEventViewModel.EVENT_DESCRIPTION.Substring(0, Math.Min(oEventViewModel.EVENT_DESCRIPTION.Length, 150)) + "..."; #region Send Push Notification var lstApplicationUsers = this.oIUserServices.lGetApplicationUsers(this.CurrentApplicationID, Convert.ToInt32(enumUserType.MobileUser).ToString()); if (lstApplicationUsers.Count > 0) { string sDeviceIDS = string.Join(",", lstApplicationUsers.Where(o => Convert.ToInt32(o.PREFERED_LANGUAGE_ID) == (int)this.CurrentApplicationLanguage) .Where(o => o.DEVICE_ID != null) .Where(o => o.DEVICE_ID != string.Empty) .Where(o => o.IS_ACTIVE == true) .Where(o => o.IS_BLOCKED == false) .Select(o => o.DEVICE_ID.ToString())); string sMobileNumbers = string.Join(",", lstApplicationUsers.Where(o => Convert.ToInt32(o.PREFERED_LANGUAGE_ID) == (int)this.CurrentApplicationLanguage) .Where(o => o.DEVICE_ID != null) .Where(o => o.DEVICE_ID != string.Empty) .Where(o => o.IS_ACTIVE == true) .Where(o => o.IS_BLOCKED == false) .Select(o => o.PHONE_NUMBER.ToString())); PushNotification oPushNotification = new PushNotification(); oPushNotification.NotificationType = enmNotificationType.Events; oPushNotification.sHeadings = sEventName; oPushNotification.sContent = sEventDesc; oPushNotification.sDeviceID = sDeviceIDS; oPushNotification.enmLanguage = this.CurrentApplicationLanguage; oPushNotification.sRecordID = oResponseResult.ResponseCode; oPushNotification.sOneSignalAppID = this.CurrentApplicationOneSignalID; oPushNotification.sOneSignalAuthKey = this.CurrentApplicationOneSignalAuthKey; oPushNotification.SendPushNotification(); NotificationLogViewModel oNotificationLogViewModel = new NotificationLogViewModel(); oNotificationLogViewModel.APPLICATION_ID = this.CurrentApplicationID; oNotificationLogViewModel.NOTIFICATION_TYPE = "events"; oNotificationLogViewModel.REQUEST_JSON = oPushNotification.sRequestJSON; oNotificationLogViewModel.RESPONSE_MESSAGE = oPushNotification.sResponseResult; oNotificationLogViewModel.MOBILE_NUMBERS = sMobileNumbers; oNotificationLogViewModel.IS_SENT_NOTIFICATION = oPushNotification.bIsSentNotification; oICommonServices.oInsertNotificationLog(oNotificationLogViewModel); #endregion } } this.OperationResultMessages = CommonResx.MessageAddSuccess; break; case enumOperationResult.Faild: this.OperationResultMessages = CommonResx.MessageAddFailed; break; } return(Json( new { nResult = this.OperationResult, sResultMessages = this.OperationResultMessages }, JsonRequestBehavior.AllowGet)); }
/// <summary> /// Sets and uploads the file from a HttpPostedFileWrapper object as the property value /// </summary> /// <param name="content"><see cref="IContentBase"/> to add property value to</param> /// <param name="propertyTypeAlias">Alias of the property to save the value on</param> /// <param name="value">The <see cref="HttpPostedFileWrapper"/> containing the file that will be uploaded</param> public static void SetValue(this IContentBase content, string propertyTypeAlias, HttpPostedFileWrapper value) { // Ensure we get the filename without the path in IE in intranet mode // http://stackoverflow.com/questions/382464/httppostedfile-filename-different-from-ie var fileName = value.FileName; if (fileName.LastIndexOf(@"\") > 0) { fileName = fileName.Substring(fileName.LastIndexOf(@"\") + 1); } var name = IOHelper.SafeFileName(fileName); if (string.IsNullOrEmpty(name) == false) { SetFileOnContent(content, propertyTypeAlias, name, value.InputStream); } }
/// <summary> /// 上传文件并返回缩略图大小 /// </summary> /// <param name="postedFile">上传的文件对象</param> /// <param name="key">服务端配置索引名</param> /// <param name="fileInfor">文件上传后返回的信息对象</param> /// <param name="thumbnailInfo">缩略图信息</param> /// <returns></returns> public static FileMessage UploadFileAndReturnInfo(HttpPostedFile postedFile, string key, out FileInfor fileInfor, out ThumbnailInfo thumbnailInfo) { HttpPostedFileBase obj = new HttpPostedFileWrapper(postedFile); return(UploadFileAndReturnInfo(obj, key, out fileInfor, out thumbnailInfo)); }
public ActionResult ExhibitReg(userModel model, HttpPostedFileWrapper file) { try { var files = Request.Files; DateTime nowtime = DateTime.Now; Session["nowtime"] = nowtime; DateTime weektime = nowtime.AddDays(7); Session["weektime"] = weektime; string path = System.IO.Path.GetFileName(file.FileName); if (file.FileName == "") { ViewBag.imger = "エラーです"; } else { file.SaveAs("C:\\UploadedFiles\\" + path); } string hp = ConfigurationManager.ConnectionStrings["Hp"].ConnectionString; using (MySqlConnection hpin = new MySqlConnection(hp)) { using (MySqlCommand cmd = hpin.CreateCommand()) { hpin.Open(); cmd.CommandText = @"select * from exhibit where ( id = " + model.id + ")"; using (MySqlDataReader sel = cmd.ExecuteReader()) { if (sel.Read() == true) { ModelState.AddModelError(string.Empty, "入力したIDは既に使用されています。"); return(View()); } else { sel.Close(); cmd.CommandText = @"insert ignore into exhibit (id,title,detail,money,price,time,lasttime,image) values(" + model.id + ",'" + model.title + "','" + model.detail + "','" + model.money + "','" + model.price + "','" + nowtime + "','" + weektime + "',load_file(" + "'C:/UploadedFiles/" + path + "'))"; cmd.ExecuteNonQuery(); cmd.CommandText = $"create table item_{model.id} (id int, title varchar(50), money int, price int, time datetime, lasttime datetime)"; cmd.ExecuteNonQuery(); cmd.CommandText = $"insert ignore into item_{model.id} (id,title,money,price,time,lasttime) values(" + model.id + ",'" + model.title + "','" + model.money + "','" + model.price + "','" + nowtime + "','" + weektime + "')"; cmd.ExecuteNonQuery(); return(RedirectToAction("AcList")); } } } } } catch (System.Exception er) { byte[] error; using (System.IO.MemoryStream ms = new MemoryStream()) using (System.IO.StreamWriter sw = new StreamWriter(ms, System.Text.Encoding.GetEncoding("utf-8"))) { string raw = er.ToString(); sw.WriteLine(raw); sw.Flush(); error = ms.ToArray(); } return(File(error, "text", "error.txt")); } }
public string UploadImage() { var memberService = DependencyResolver.Current.GetService <IMembershipService>(); var roleService = DependencyResolver.Current.GetService <IRoleService>(); var localizationService = DependencyResolver.Current.GetService <ILocalizationService>(); var uploadService = DependencyResolver.Current.GetService <IUploadedFileService>(); var context = DependencyResolver.Current.GetService <IMvcForumContext>(); var loggingService = DependencyResolver.Current.GetService <ILoggingService>(); try { if (HttpContext.Current.Request.Files.AllKeys.Any()) { // Get the uploaded image from the Files collection var httpPostedFile = HttpContext.Current.Request.Files["file"]; if (httpPostedFile != null) { HttpPostedFileBase photo = new HttpPostedFileWrapper(httpPostedFile); var loggedOnReadOnlyUser = memberService.GetUser(HttpContext.Current.User.Identity.Name); var permissions = roleService.GetPermissions(null, loggedOnReadOnlyUser.Roles.FirstOrDefault()); // Get the permissions for this category, and check they are allowed to update if (permissions[SiteConstants.Instance.PermissionInsertEditorImages].IsTicked && loggedOnReadOnlyUser.DisableFileUploads != true) { // woot! User has permission and all seems ok // Before we save anything, check the user already has an upload folder and if not create one var uploadFolderPath = HostingEnvironment.MapPath( string.Concat(SiteConstants.Instance.UploadFolderPath, loggedOnReadOnlyUser.Id)); if (!Directory.Exists(uploadFolderPath)) { Directory.CreateDirectory(uploadFolderPath); } // If successful then upload the file var uploadResult = AppHelpers.UploadFile(photo, uploadFolderPath, localizationService, true); if (!uploadResult.UploadSuccessful) { return(string.Empty); } // Add the filename to the database var uploadedFile = new UploadedFile { Filename = uploadResult.UploadedFileName, MembershipUser = loggedOnReadOnlyUser }; uploadService.Add(uploadedFile); // Commit the changes context.SaveChanges(); return(uploadResult.UploadedFileUrl); } } } } catch (Exception ex) { context.RollBack(); loggingService.Error(ex); } return(string.Empty); }
public JsonResult validate() { //sacando la cedula var cedula = System.Web.HttpContext.Current.Request.Form["HelpCedula"]; //sacando los archivos var pic = System.Web.HttpContext.Current.Request.Files["HelpSectionImages"]; HttpPostedFileBase filebase = new HttpPostedFileWrapper(pic); string FileStr = null; string fileName = ""; if (filebase != null) { if (filebase.FileName != null) { fileName = filebase.FileName; } FileStr = PaseToBase64(filebase); } PruebaBizagi.WorkFlowBizagiService.WorkflowEngineSOASoapClient serv = new PruebaBizagi.WorkFlowBizagiService.WorkflowEngineSOASoapClient(); // using System.Xml; //creando caso String rawXml = @"<BizAgiWSParam> <domain>domain</domain> <userName>oficial02</userName> <Cases> <Case> <Process>LoanRequest</Process> <Entities> <LoanRequest> </LoanRequest> </Entities> </Case> </Cases> </BizAgiWSParam>"; XmlDocument xmlDoc = new XmlDocument(); xmlDoc.LoadXml(rawXml); var resultsss = serv.createCases(xmlDoc); if (resultsss.SelectSingleNode("process/processId").InnerXml != null && resultsss.SelectSingleNode("process/processId").InnerXml != "") { //realizando la primera actividad. var caseid = resultsss.SelectSingleNode("process/processId").InnerXml; String rawXml2 = @"<BizAgiWSParam> <domain>domain</domain> <userName>Oficial02</userName> <ActivityData> <idCase>" + caseid + @"</idCase> <taskName>Registrar</taskName> </ActivityData> <Entities> <LoanRequest> <TGEN_Oficina> <idTGEN_SUCURSAL>4</idTGEN_SUCURSAL> <OFI_NOMBRE>SUC. FERRETERIA OCHOA</OFI_NOMBRE> <OFI_CODSUC>3</OFI_CODSUC> </TGEN_Oficina> <TGEN_Sucursal> <SUC_CODIGO>3</SUC_CODIGO> <SUC_NOMBRE>FERRETERIA OCHOA</SUC_NOMBRE> </TGEN_Sucursal> <Promocion>1</Promocion> <DocumentTypes>1</DocumentTypes> <DocumentNumber>224-0018986-0</DocumentNumber> <LogInvokeServices> </LogInvokeServices> </LoanRequest> </Entities> </BizAgiWSParam>"; XmlDocument xmlDoc2 = new XmlDocument(); xmlDoc2.LoadXml(rawXml2); var resultsss2 = serv.performActivity(xmlDoc2); var strng3 = ""; if (FileStr != null) { strng3 = @" <BizAgiWSParam> <domain>domain</domain> <userName>Oficial02</userName> <ActivityData> <idCase>" + caseid + @"</idCase> <taskName>Info_ValCredito</taskName> </ActivityData> <Entities> <LoanRequest> <LoanDocuments> <IdentificationFile> <File fileName=" + '\u0022' + fileName + '\u0022' + @">" + FileStr + @"</File> </IdentificationFile> </LoanDocuments> <TasaConfig>6</TasaConfig> <CredinetInitialData> <CodigoPromotor>852336</CodigoPromotor> <VendedorBanco>Miguel Martinez</VendedorBanco> <Dealer>6</Dealer> <VendedorDealer>Jefferson Connor</VendedorDealer> <SubProducto>5</SubProducto> <TipoDocVehiculo> <idTipoDocVehiculo>1</idTipoDocVehiculo> <Descripcion>Matrícula</Descripcion> </TipoDocVehiculo> <TIPOVEHICULO> <DES_CODIGO>1</DES_CODIGO> <DES_DESCRIPCION>VEHICULO</DES_DESCRIPCION> <DES_TUCodigo>1</DES_TUCodigo> </TIPOVEHICULO> <MODELO>94</MODELO> <MARCA>1</MARCA> <ANOFABVEHICULO>2017</ANOFABVEHICULO> <TASATOTAL_CFG>14.95</TASATOTAL_CFG> <TASA_PACTADA>14.95</TASA_PACTADA> <Frecuencia> <idFrecuencia>4</idFrecuencia> <Description>Mensual</Description> <Fre_Cod>4</Fre_Cod> </Frecuencia> <Period>1</Period> <Moneda> <idTEGEN_MONEDA>4</idTEGEN_MONEDA> <MON_DESC>PESOS DOMINICANOS</MON_DESC> <MON_ABR>RD$</MON_ABR> <MON_COD>0</MON_COD> </Moneda> <MontoSolicitado>400000</MontoSolicitado> <VALOR>600000</VALOR> <CONDICION>2</CONDICION> <TELEFONOCELULAR>809-652-8008</TELEFONOCELULAR> <FuenteIngreso>1</FuenteIngreso> <INGRESOSMENSUALES>85000</INGRESOSMENSUALES> <TIPOVIVIENDA>1</TIPOVIVIENDA> <LUGARTRABAJO>Banco StartNew</LUGARTRABAJO> <PosicionActual>Ing Analista</PosicionActual> <AnoServicio>5</AnoServicio> </CredinetInitialData> <LogInvokeServices> </LogInvokeServices> </LoanRequest> </Entities> </BizAgiWSParam>"; } else { strng3 = @" <BizAgiWSParam> <domain>domain</domain> <userName>Oficial02</userName> <ActivityData> <idCase>" + caseid + @"</idCase> <taskName>Info_ValCredito</taskName> </ActivityData> <Entities> <LoanRequest> <TasaConfig>6</TasaConfig> <CredinetInitialData> <CodigoPromotor>852336</CodigoPromotor> <VendedorBanco>Miguel Martinez</VendedorBanco> <Dealer>6</Dealer> <VendedorDealer>Jefferson Connor</VendedorDealer> <SubProducto>5</SubProducto> <TipoDocVehiculo> <idTipoDocVehiculo>1</idTipoDocVehiculo> <Descripcion>Matrícula</Descripcion> </TipoDocVehiculo> <TIPOVEHICULO> <DES_CODIGO>1</DES_CODIGO> <DES_DESCRIPCION>VEHICULO</DES_DESCRIPCION> <DES_TUCodigo>1</DES_TUCodigo> </TIPOVEHICULO> <MODELO>94</MODELO> <MARCA>1</MARCA> <ANOFABVEHICULO>2017</ANOFABVEHICULO> <TASATOTAL_CFG>14.95</TASATOTAL_CFG> <TASA_PACTADA>14.95</TASA_PACTADA> <Frecuencia> <idFrecuencia>4</idFrecuencia> <Description>Mensual</Description> <Fre_Cod>4</Fre_Cod> </Frecuencia> <Period>1</Period> <Moneda> <idTEGEN_MONEDA>4</idTEGEN_MONEDA> <MON_DESC>PESOS DOMINICANOS</MON_DESC> <MON_ABR>RD$</MON_ABR> <MON_COD>0</MON_COD> </Moneda> <MontoSolicitado>400000</MontoSolicitado> <VALOR>600000</VALOR> <CONDICION>2</CONDICION> <TELEFONOCELULAR>809-652-8008</TELEFONOCELULAR> <FuenteIngreso>1</FuenteIngreso> <INGRESOSMENSUALES>85000</INGRESOSMENSUALES> <TIPOVIVIENDA>1</TIPOVIVIENDA> <LUGARTRABAJO>Banco StartNew</LUGARTRABAJO> <PosicionActual>Ing Analista</PosicionActual> <AnoServicio>5</AnoServicio> </CredinetInitialData> <LogInvokeServices> </LogInvokeServices> </LoanRequest> </Entities> </BizAgiWSParam>"; } XmlDocument final = new XmlDocument(); final.LoadXml(strng3); var tmpResult = serv.performActivity(final); } var result = new PadronResponse(); var repo = new Repository(); result = repo.getPadron(cedula); byte[] newBytes = Convert.FromBase64String(result.foto); result.fotobyte = newBytes; return(Json(result)); }
public ActionResult Index(HttpPostedFileWrapper CustomerFile, HttpPostedFileWrapper ToolFile, HttpPostedFileWrapper RentalFile) { try { if (ModelState.IsValid) { if (CustomerFile != null && CustomerFile.ContentLength > 0 && ToolFile != null && ToolFile.ContentLength > 0 && RentalFile != null && RentalFile.ContentLength > 0) { CustomerFile.SaveAs(Server.MapPath("~/DataFiles/Customers.txt")); ToolFile.SaveAs(Server.MapPath("~/DataFiles/Tools.txt")); RentalFile.SaveAs(Server.MapPath("~/DataFiles/Rental_data.txt")); ShowNotification("Success", "DataFiles Saved successfully. Use Other Modules with changed data.", "success"); return(View()); } else { ShowNotification("Error", "Doesn't upload any file OR Upload Empty File", "warning"); return(View()); } } return(View()); } catch { ShowNotification("Error", "Error while saving Files.", "warning"); return(View()); } }
/// <summary> /// 文件上传操作 /// </summary> public override void Process() { HttpPostedFile imgfile = (HttpPostedFile)Request.Files[UploadConfig.UploadFieldName]; HttpPostedFileBase fileBase = new HttpPostedFileWrapper(imgfile) as HttpPostedFileBase; string uploadFileName1 = imgfile.FileName; if (!CheckFileType(uploadFileName1)) { Result.State = UploadState.TypeNotAllow; WriteResult(); return; } if (!CheckFileSize(imgfile.ContentLength)) { Result.State = UploadState.SizeLimitExceed; WriteResult(); return; } Result.OriginFileName = uploadFileName1; string addr; var ret = _QiniuImgBiz.UploadStream(fileBase.InputStream, uploadFileName1, out addr); //ImgUploadRet imgRet = ImgUtil.UploadImag(fileBase); if (ret) { Result.Url = addr; Result.State = UploadState.Success; } else { Result.State = UploadState.NetworkError; Result.ErrorMessage = "上传错误"; } WriteResult(); return; #region 注释 //byte[] uploadFileBytes = null; //string uploadFileName = null; //if (UploadConfig.Base64) //{ // uploadFileName = UploadConfig.Base64Filename; // uploadFileBytes = Convert.FromBase64String(Request[UploadConfig.UploadFieldName]); //} //else //{ // var file = Request.Files[UploadConfig.UploadFieldName]; // uploadFileName = file.FileName; // if (!CheckFileType(uploadFileName)) // { // Result.State = UploadState.TypeNotAllow; // WriteResult(); // return; // } // if (!CheckFileSize(file.ContentLength)) // { // Result.State = UploadState.SizeLimitExceed; // WriteResult(); // return; // } // uploadFileBytes = new byte[file.ContentLength]; // try // { // file.InputStream.Read(uploadFileBytes, 0, file.ContentLength); // } // catch (Exception) // { // Result.State = UploadState.NetworkError; // WriteResult(); // } //} //Result.OriginFileName = uploadFileName; //var savePath = PathFormatter.Format(uploadFileName, UploadConfig.PathFormat); //var localPath = Server.MapPath(savePath); //try //{ // if (!Directory.Exists(Path.GetDirectoryName(localPath))) // { // Directory.CreateDirectory(Path.GetDirectoryName(localPath)); // } // File.WriteAllBytes(localPath, uploadFileBytes); // Result.Url = savePath; // Result.State = UploadState.Success; //} //catch (Exception e) //{ // Result.State = UploadState.FileAccessError; // Result.ErrorMessage = e.Message; //} //finally //{ // WriteResult(); //} #endregion }
public ActionResult UploadForm(HttpPostedFileWrapper upload) { return(View()); }
public JsonResult JSaveApplicationLogoToTemp() { Response oResponseResult = new Response(); string sRealFileName = string.Empty; string sModifiedFileName = string.Empty; string sFullFilePath = string.Empty; if (System.Web.HttpContext.Current.Request.Files.AllKeys.Any()) { var oFile = System.Web.HttpContext.Current.Request.Files["ApplicationLogoFile"]; HttpPostedFileBase filebase = new HttpPostedFileWrapper(oFile); sRealFileName = filebase.FileName; sModifiedFileName = CommonHelper.AppendTimeStamp(filebase.FileName); FileAccessHandler oFileAccessHandler = new FileAccessHandler(); //DirectoryPath = TempUploadFolder from web.config string sDirectoryPath = string.Concat(CommonHelper.sGetConfigKeyValue(ConstantNames.TempUploadFolder)); sFullFilePath = Path.Combine(sDirectoryPath, sModifiedFileName); oFileAccessHandler.CreateDirectory(sDirectoryPath); if (oFileAccessHandler.OperationResult == 1) { oFileAccessHandler.WirteFile(sFullFilePath, filebase.InputStream); if (oFileAccessHandler.OperationResult == 1) { this.OperationResult = enumOperationResult.Success; } else { this.OperationResult = enumOperationResult.Faild; } } else { this.OperationResult = enumOperationResult.Faild; } } switch (this.OperationResult) { case enumOperationResult.Success: this.OperationResultMessages = CommonResx.MessageAddSuccess; break; case enumOperationResult.Faild: this.OperationResultMessages = CommonResx.MessageAddFailed; break; case enumOperationResult.AlreadyExistRecordFaild: this.OperationResultMessages = CommonResx.AlreadyExistRecordFaild; break; } return(Json( new { nResult = this.OperationResult, sResultMessages = this.OperationResultMessages, sFileName = (this.OperationResult == enumOperationResult.Success) ? sModifiedFileName : string.Empty, sFullFilePath = (this.OperationResult == enumOperationResult.Success) ? sFullFilePath.Replace('\\', '/') : string.Empty }, JsonRequestBehavior.AllowGet)); }