Come caricare l’immagine tramite WebApi

Come posso caricare il file immagine tramite l’ API Web ASP.NET ?
Ho un tag di input in modalità File e pubblicato su API, come posso salvarlo nella cartella del server
Ho provato questo codice ma non ha funzionato:

private void UploadWholeFile(HttpRequestBase request) { for (int i = 0; i < request.Files.Count; i++) { var file = request.Files[i]; var ext = new FileInfo(file.FileName).Extension; var fullPath = Path.Combine(StorageRoot, Path.GetFileName(Guid.NewGuid() + ext)); file.SaveAs(fullPath); } } 

Qui ho descritto l’intero processo per caricare l’immagine in web api

 [Route("user/PostUserImage")] public async Task PostUserImage() { Dictionary dict = new Dictionary(); try { var httpRequest = HttpContext.Current.Request; foreach (string file in httpRequest.Files) { HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created); var postedFile = httpRequest.Files[file]; if (postedFile != null && postedFile.ContentLength > 0) { int MaxContentLength = 1024 * 1024 * 1; //Size = 1 MB IList AllowedFileExtensions = new List { ".jpg", ".gif", ".png" }; var ext = postedFile.FileName.Substring(postedFile.FileName.LastIndexOf('.')); var extension = ext.ToLower(); if (!AllowedFileExtensions.Contains(extension)) { var message = string.Format("Please Upload image of type .jpg,.gif,.png."); dict.Add("error", message); return Request.CreateResponse(HttpStatusCode.BadRequest, dict); } else if (postedFile.ContentLength > MaxContentLength) { var message = string.Format("Please Upload a file upto 1 mb."); dict.Add("error", message); return Request.CreateResponse(HttpStatusCode.BadRequest, dict); } else { YourModelProperty.imageurl = userInfo.email_id + extension; // where you want to attach your imageurl //if needed write the code to update the table var filePath = HttpContext.Current.Server.MapPath("~/Userimage/" + userInfo.email_id + extension); //Userimage myfolder name where i want to save my image postedFile.SaveAs(filePath); } } var message1 = string.Format("Image Updated Successfully."); return Request.CreateErrorResponse(HttpStatusCode.Created, message1); ; } var res = string.Format("Please Upload a image."); dict.Add("error", res); return Request.CreateResponse(HttpStatusCode.NotFound, dict); } catch (Exception ex) { var res = string.Format("some Message"); dict.Add("error", res); return Request.CreateResponse(HttpStatusCode.NotFound, dict); } } 

Imposta questo codice (tratto da http://www.c-sharpcorner.com/uploadfile/fc9f65/uploading-a-file-with-web-api-and-entity-framework-using-aja/ ) sul post dell’API WEB controller:

  // POST: api/FileUploads [ResponseType(typeof(FileUpload))] public IHttpActionResult PostFileUpload() { if (HttpContext.Current.Request.Files.AllKeys.Any()) { // Get the uploaded image from the Files collection var httpPostedFile = HttpContext.Current.Request.Files["UploadedImage"]; if (httpPostedFile != null) { FileUpload imgupload = new FileUpload(); int length = httpPostedFile.ContentLength; imgupload.imagedata = new byte[length]; //get imagedata httpPostedFile.InputStream.Read(imgupload.imagedata, 0, length); imgupload.imagename = Path.GetFileName(httpPostedFile.FileName); db.FileUploads.Add(imgupload); db.SaveChanges(); // Make sure you provide Write permissions to destination folder string sPath = @"C:\Users\xxxx\Documents\UploadedFiles"; var fileSavePath = Path.Combine(sPath, httpPostedFile.FileName); // Save the uploaded file to "UploadedFiles" folder httpPostedFile.SaveAs(fileSavePath); return Ok("Image Uploaded"); } } return Ok("Image is not Uploaded"); } 

Nell’applicazione UWP, impostare il seguente metodo:

  using System; using System.Threading.Tasks; using Windows.Storage; using Windows.Storage.Streams; using Windows.Web.Http; // ... public static bool UploadImageToServer(StorageFile imageFile) { bool saveRes = false; try { using (HttpClient client = new HttpClient()) { if (client != null) // if no Network Connection { HttpResponseMessage response = new HttpResponseMessage(); Task task = Task.Run(async () => { using (HttpMultipartFormDataContent formData = new HttpMultipartFormDataContent()) { IBuffer buffer = await FileIO.ReadBufferAsync(imageFile); HttpBufferContent WebHTTPContent = new HttpBufferContent(buffer); formData.Add(WebHTTPContent, "UploadedImage", imageFile.Name); response = await client.PostAsync(App.VehicleImageUri, formData); if (response.IsSuccessStatusCode) saveRes = true; } }); task.Wait(); } } } catch (Exception em) { // Handle exception here ... } return saveRes; } 

Chiami il tuo metodo come segue:

 private async void CaptureImageByUser() { StorageFile file; // Create storage file in local app storage string fileName = GenerateNewFileName() + ".jpg"; CreationCollisionOption collisionOption = CreationCollisionOption.GenerateUniqueName; file = await ApplicationData.Current.TemporaryFolder.CreateFileAsync(fileName, collisionOption); // Captures and stores new Jpeg image file await mediaCapture.CapturePhotoToStorageFileAsync(ImageEncodingProperties.CreateJpeg(), file); // Delete the file in the temporary location if successfully uploaded if (SaveDataByUser.UploadImageToServer(file)) await file.DeleteAsync(); } private string GenerateNewFileName(string prefix = "IMG") { return prefix + "_" + DateTime.UtcNow.ToString("yyyy-MMM-dd_HH-mm-ss"); } 

Ehi, fammi sapere se funziona per te !! Felice di aiutare! 🙂

WebApi supporta la deserializzazione dell’array JSON , in modo che sia ansible ricevere byte dichiarando con byte[] .

Il seguente esempio mostrerà come caricare l’immagine:

 public class ImageModel { public string Name { get; set; } public byte[] Bytes { get; set; } } 

Nel tuo controller Scrivere un’immagine su disco:

 private string WriteImage(byte[] arr) { var filename = [email protected]"images\{DateTime.Now.Ticks}."; using (var im = Image.FromStream(new MemoryStream(arr))) { ImageFormat frmt; if (ImageFormat.Png.Equals(im.RawFormat)) { filename += "png"; frmt = ImageFormat.Png; } else { filename += "jpg"; frmt = ImageFormat.Jpeg; } string path = HttpContext.Current.Server.MapPath("~/") + filename; im.Save(path, frmt); } return [email protected]"http:\\{Request.RequestUri.Host}\{filename}"; } 

HttpContext.Current.Server.MapPath("~/") fornirà il percorso interno del server in esecuzione. Request.RequestUri.Host restituisce il nome host.

 public IHttpActionResult UploadImage(ImageModel model) { var imgUrl = WriteImage(model.Bytes); // Some code } 

Per inviare immagini dal browser

In HTML:

  

Metodo di caricamento per AngularJS:

 $scope.upload = function () { var file = document.getElementById("imageFile").files[0]; var r = new FileReader(); r.onloadend = function (e) { var arr = Array.from(new Uint8Array(e.target.result)); var uploadData = { Name: "Name of Image", Bytes: arr } console.log(uploadData); $http.post('api/Uploader/UploadImage', uploadData) .then( function (response) { console.log(response); }, function (reason) { console.log(reason); }) } r.readAsArrayBuffer(file); } 

Puoi semplicemente convertire la tua immagine in Base64String e postarla come String Content .

 public static async Task Post(string controller, string method, string accessToken, string bodyRequest) where T : class { using (HttpClient client = new HttpClient()) { client.DefaultRequestHeaders.Clear(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken); var stringContent = new StringContent(bodyRequest, Encoding.UTF8, "application/json"); var response = await client.PostAsync($"{Constants.ApiBaseUrl}/api/{controller}/{method}", stringContent); if (response.IsSuccessStatusCode) return response.Content as T; } return default(T); } 

bodyRequest sul mio codice è il valore class / modello da convertire in stringa

utilizzando Json.Serialize (modello) che contiene anche l’immagine System.Convert.ToBase64String (imageBytes []) come sua proprietà.

Se la tua API consente solo un’immagine alla volta, System.Web.Helpers.WebImage può essere d’aiuto. Assicurati che sia incluso un nome di file.

—— WebKitFormBoundaryzrmNUJnUirtKajVF Content-Disposition: form-data; name = “immagine”; filename = “IMG_3321.JPG” Content-Type: image / jpeg

—— WebKitFormBoundaryzrmNUJnUirtKajVF–

 [HttpPost] [ResponseType(typeof(Models.Photo))] [Route("upload")] public async Task Upload() { var img = WebImage.GetImageFromRequest(); if (img == null) { return BadRequest("Image is null."); } // Do whatever you want with the image (resize, save, ...) // In this case, I save the image to a cloud storage and // create a DB record to reference the image. }