How to save and return images with Web Api?

4

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

In my Controller of project Asp.net MVC I get from View an image of type 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 path of the image and its name, the file should be saved to a folder on the server.

Thank you.

    
asked by anonymous 06.06.2014 / 21:37

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

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

    
06.06.2014 / 22:28