How to save and return images with Web Api?

Asked

Viewed 2,717 times

4

How to send and return images from a Web Api from the Controller of an application Asp.net MVC?

In my Controller of the project Asp.net MVC I get from View a picture like HttpPostedFileBase and need to send to Web Api using PostAsJsonAsync. Ex.:

    var response = await client.PostAsJsonAsync("api/image", image);

Note: I need to save in the database only the image path and its name, the file must be saved in a folder on the server.

Thank you.

1 answer

3


Save

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;

namespace UploadApplication.Controllers
{
    public class UploadController : ApiController
    {
        public async Task<HttpResponseMessage> Post()
        { 
            // Ver se POST é MultiPart? 
            if (!Request.Content.IsMimeMultipartContent())
            {
                throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
            } 
            // Preparar CustomMultipartFormDataStreamProvider para carga de dados
            // (veja mais abaixo)

            string fileSaveLocation = HttpContext.Current.Server.MapPath("~/Diretorio/Do/Servidor"); 
            CustomMultipartFormDataStreamProvider provider = new CustomMultipartFormDataStreamProvider(fileSaveLocation); 
            List<string> files = new List<string>(); 
            try
            {
                // Ler conteúdo da requisição para CustomMultipartFormDataStreamProvider. 
                await Request.Content.ReadAsMultipartAsync(provider);

                foreach (MultipartFileData file in provider.FileData)
                {
                    files.Add(Path.GetFileName(file.LocalFileName));
                } 
                // OK se tudo deu certo.
                return Request.CreateResponse(HttpStatusCode.OK, files);
            }
            catch (System.Exception e) { 
                return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e); 
            }
        }
    }

    public class CustomMultipartFormDataStreamProvider : MultipartFormDataStreamProvider
    {
        public CustomMultipartFormDataStreamProvider(string path) : base(path) { }

        public override string GetLocalFileName(HttpContentHeaders headers)
        {
            return headers.ContentDisposition.FileName.Replace("\"", string.Empty);
        }
    }
}

Return

That depends on how you want to do it. If the image is hosted on the server, I think the traditional (return path in JSON) is the most appropriate.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.