Error sending file through PostAsJsonAsync method in Asp.Net MVC

3

In my Controller of a Asp.net MVC project I get from View an image of type HttpPostedFileBase and need to send Web Api using PostAsJsonAsync :

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

The image is coming normally, but when you get to the line above, this error appears:

"Error getting value from 'ReadTimeout' on 'System.Web.HttpInputStream'."

Note: sending "image.InputStream" gives the same error.

How to solve this problem? Thank you.

Update: Web Api implemented based on this response: How to save and return images with Api Web?

    
asked by anonymous 26.06.2014 / 16:03

1 answer

2

Example:

This class will serve as the basis for transporting the image with its name and byte array.

public class Transporte
{
    public string Name { get; set; }
    public byte[] Imagem { get; set; }
}

Action Methods (Web MVC)

[HttpGet]
public ActionResult EnviarImagem()
{
    return View();
}

[HttpPost]
public void EnviarImagem(HttpPostedFileBase imagem)
{
    int tam = (int)imagem.InputStream.Length;
    byte[] imgByte = new byte[tam];
    imagem.InputStream.Read(imgByte, 0, tam);

    HttpClient web = new HttpClient();
    web.BaseAddress = new Uri("http://localhost:17527/");
    HttpResponseMessage response = web.PostAsJsonAsync("api/GravarImagem", new Transporte() { Imagem = imgByte, Name = imagem.FileName }).Result;            
}

View for these methods

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>EnviarImagem</title>
</head>
<body>
    <div> 
        <form method="post" action="/Home/EnviarImagem" enctype="multipart/form-data">
            <input type="file" name="imagem" id="imagem" />
            <button>Enviar</button>
        </form>
    </div>
</body>
</html>

Api Web

public class RecebeController : ApiController
{
    [HttpPost]
    [Route("api/GravarImagem")]
    public HttpResponseMessage GravarImagem(Transporte transporte)
    {
        File.WriteAllBytes(HttpContext.Current.Server.MapPath("~/Fotos/") + transporte.Name, transporte.Imagem);
        return Request.CreateResponse();
    }
}

Debug:

    
26.06.2014 / 17:54