Example:
This class will serve as the basis for transporting the image with its name and the 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 referring to 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>
Web Api
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:
If you have the code, ie the methods? you can post?
– user6026
You don’t have to use image.Inputstream?
– f.fujihara
@f. fujihara I tried to send the image.Inputstream and gives the same error.
– user8356
the method it receives and send to the webapi (both if possible)
– user6026
@Harrypotter made the based on that answer, but I haven’t tested yet pq I have this problem that prevents the image from getting there: http://answall.com/a/19461/8356
– user8356
What you want to do with the image?
– f.fujihara
@f. fujihara have an Asp.net mvc project that in the controller gets this image from View and I want to send it to another Web Api project. In this project I want to receive the image and save it in a directory. In short: save the image and be able to return it, using the Asp.net MVC together Web Api (separate projects that are in the same Solution). What I’m trying to do is this: http://answall.com/questions/19454/como-salvar-e-retornar-imagens-com-web-api
– user8356
You receive an Httppostedfilebase parameter in the Controller, and if in Business Voce you receive a Stream? parameter (image.Inputstream). It would be easier for you to manipulate and send to another directory.
– f.fujihara
Well I posted an example of how I would, I hope it helps, @Carlosgeovanio
– user6026
@Harrypotter I’ll test that answer of yours, thank you very much.
– user8356
OK @Carlosgeovanio
– user6026
It worked @Carlosgeovanio ?
– user6026
gave yes @Harrypotter. Thank you very much.
– user8356
if you can close the question to serve as a model for others
– user6026