public async Task <Reply> Photo([FromUri] AnimalPictureViewModel model) { Reply oR = new Reply(); oR.result = 0; //Subir el archivo a las carpeta por medio de esta ruta. string root = HttpContext.Current.Server.MapPath("~/App_Data"); var provider = new MultipartFormDataStreamProvider(root); if (!Verify(model.token)) { oR.message = "No Autorizado"; return(oR); } //view multipart if (!Request.Content.IsMimeMultipartContent()) { oR.message = "No viene imagen"; return(oR); } //Asegurar que termine el proceso await Request.Content.ReadAsMultipartAsync(provider); FileInfo fileInfoPicture = null; foreach (MultipartFileData fileData in provider.FileData) { if (fileData.Headers.ContentDisposition.Name.Equals("pictue")) { fileInfoPicture = new FileInfo(fileData.LocalFileName); } } if (fileInfoPicture != null) { using (FileStream fs = fileInfoPicture.Open(FileMode.Open, FileAccess.Read)) { byte[] b = new byte[fileInfoPicture.Length]; UTF8Encoding temp = new UTF8Encoding(true); while (fs.Read(b, 0, b.Length) > 0) { ; } try { }catch (Exception ex) { oR.message = "Intente mas tarde"; } } } return(oR); }
public async Task <Reply> Photo([FromUri] AnimalPictureViewModel model) { Reply oR = new Reply(); oR.Result = 0; string root = HttpContext.Current.Server.MapPath("~/App_Data"); var provider = new MultipartFormDataStreamProvider(root); if (!Verify(model.token)) { oR.Message = "No Autorizado"; return(oR); } // Verificar si viene multipart if (!Request.Content.IsMimeMultipartContent()) { oR.Message = "No viene imagen"; return(oR); } await Request.Content.ReadAsMultipartAsync(provider); FileInfo fileInfoPicture = null; foreach (MultipartFileData fileData in provider.FileData) { if (fileData.Headers.ContentDisposition.Name.Replace("\\", "").Replace("\"", "").Equals("picture")) { fileInfoPicture = new FileInfo(fileData.LocalFileName); } } if (fileInfoPicture != null) { // Guardar el archivo using (FileStream fs = fileInfoPicture.Open(FileMode.Open, FileAccess.Read)) { byte[] b = new byte[fileInfoPicture.Length]; UTF8Encoding temp = new UTF8Encoding(true); while (fs.Read(b, 0, b.Length) > 0) { ; } // Guardar el archivo try { using (NorthwindDBCon db = new NorthwindDBCon()) { var oAnimal = db.Animals.Find(model.Id); oAnimal.Picture = b; db.Entry(oAnimal).State = EntityState.Modified; db.SaveChanges(); oR.Result = 1; } } catch (Exception ex) { oR.Message = "Intenta mas tarde."; } } } return(oR); }
public async Task <Reply> Photo([FromUri] AnimalPictureViewModel model) { Reply oReply = new Reply(); oReply.result = 0; string root = HttpContext.Current.Server.MapPath("~/App_Data"); var provider = new MultipartFormDataStreamProvider(root); if (!verificarToken(model.token)) { oReply.message = "Usuario no Autorizado"; return(oReply); } //viene multipart if (!Request.Content.IsMimeMultipartContent()) { oReply.message = "no viene imagen en el contenido"; return(oReply); } await Request.Content.ReadAsMultipartAsync(provider); FileInfo fileInfoPicture = null; foreach (MultipartFileData filePhoto in provider.FileData) { if (filePhoto.Headers.ContentDisposition.Name.Replace("\"", "").Replace("\\", "").Equals("picture")) { fileInfoPicture = new FileInfo(filePhoto.LocalFileName); } } if (fileInfoPicture != null) { using (FileStream fs = fileInfoPicture.Open(FileMode.Open, FileAccess.Read)) { byte[] b = new byte[fileInfoPicture.Length]; UTF8Encoding temp = new UTF8Encoding(true); while (fs.Read(b, 0, b.Length) > 0) { ; } try { using (var db = new mvcApiEntities()) { var oAnimal = db.animal.Find(model.Id); oAnimal.picture = b; db.Entry(oAnimal).State = System.Data.Entity.EntityState.Modified; db.SaveChanges(); oReply.result = 1; oReply.message = "Se actualizo la imagen"; } } catch (Exception ex) { oReply.message = "Error al leer y cargar a la matriz de bytes"; } } } return(oReply); }
public async Task <Reply> Photo([FromUri] AnimalPictureViewModel model) { var oReply = new Reply(); oReply.result = 0; string root = HttpContext.Current.Server.MapPath("~/App_Data"); var provider = new MultipartFormDataStreamProvider(root); if (!Verify(model.token)) { oReply.message = "Not authorized"; return(oReply); } if (!Request.Content.IsMimeMultipartContent()) { oReply.message = "Doesn't contain image"; return(oReply); } await Request.Content.ReadAsMultipartAsync(provider); FileInfo oFileInfoPicture = null; foreach (var item in provider.FileData) { // Didn't work with this 'if' line. if (item.Headers.ContentDisposition.Name.Replace("\\", "").Replace("\"", "").Equals("picture")) { oFileInfoPicture = new FileInfo(item.LocalFileName); } } if (oFileInfoPicture != null) { using (FileStream oFileStream = oFileInfoPicture.Open(FileMode.Open, FileAccess.Read)) { byte[] b = new byte[oFileInfoPicture.Length]; var temp = new UTF8Encoding(true); while (oFileStream.Read(b, 0, b.Length) > 0) { ; } try { using (var dbContext = new Example002Entities()) { var oAnimal = dbContext.Animals.Find(model.Id); oAnimal.picture = b; dbContext.Entry(oAnimal).State = System.Data.Entity.EntityState.Modified; dbContext.SaveChanges(); oReply.result = 1; } } catch (Exception exception) { oReply.message = string.Format("Try again later. {0}", exception); } } } return(oReply); }
public async Task <Reply> Photo([FromUri] AnimalPictureViewModel model) // Asincrono que permite ejecutar hilos, para dar respuesta al cliente, mientras se procesa la solicitud. Recibe token { Reply oReply = new Reply(); oReply.result = 0; // Se crea ruta para almacenar, correspondiente a carpeta App_Data, donde se almacenan archvios temporales cuando se cargan string root = HttpContext.Current.Server.MapPath("~/App_Data"); // Se crea proveedor para poder leer el multipart var provider = new MultipartFormDataStreamProvider(root); // Permite nutrir el provider, cuando el archivo sea subido por multipart if (!Verify(model.token)) { oReply.message = " Error en autenticación..."; return(oReply); } // Validación de multipart if (!Request.Content.IsMimeMultipartContent()) // Si la solicitud no es multipart, entonces: { oReply.message = " No viene imagen..."; return(oReply); } // Lectura del archivo // Await indica que espere, hasta que se envíe el archivo del multipart await Request.Content.ReadAsMultipartAsync(provider); // Se crea dato tipo fileinfo que tiene información de la imagen FileInfo fileInfoPicture = null; // Foreach en caso de que se envíe más de una imagen foreach (MultipartFileData fileData in provider.FileData) { if (fileData.Headers.ContentDisposition.Name.Replace("\\", "").Replace("\"", "").Equals("picture")) { fileInfoPicture = new FileInfo(fileData.LocalFileName); // Agrega archivo a ruta, siempre y cuando tenga como nombre picture } } // Si todo salió bien if (fileInfoPicture != null) { // Se pasa de tener imagen en temporal, a fileinfo, filestream y ahora a una matriz de bytes using (FileStream fs = fileInfoPicture.Open(FileMode.Open, FileAccess.Read)) { byte[] b = new byte[fileInfoPicture.Length]; // El tamaño de la matriz, lo da el lenght del fileinfopicture UTF8Encoding temp = new UTF8Encoding(true); // Codificación // El stream se va a escribir en la matriz while (fs.Read(b, 0, b.Length) > 0) { ; // Lee linea por linea la matriz de bytes generada de la imagen } // Se guarda con un TryCatch por si falla algo try { using (Cursomvc_apiEntities DB = new Cursomvc_apiEntities()) { // Como si fuera un update var oAnimal = DB.animal.Find(model.id); oAnimal.picture = b; DB.Entry(oAnimal).State = System.Data.Entity.EntityState.Modified; DB.SaveChanges(); oReply.result = 1; } } catch (Exception ex) { oReply.message = "Error procesando imagen: " + ex; return(oReply); } } } return(oReply); }