0

The goal I'm trying to accomplish is simply requesting an image from an API, and returning it to the client-side in the form of an append method.

NO, I cannot just handle this in client side altogether because of a user/pass requirement for the API.

NO, I cannot use @Url.Action(ImageFromPath) method in the src of the image.

That said, here's my back-end code:

[HttpGet("api/GetImage")]
public ActionResult ImageFromPath()
{
    string URL = "http://user:pass@MYIPADDRESS/cgi-bin/snapshot.cgi?c=1&authbasic=asdf1234";

    var srcImage = Image.FromFile(URL);
    var stream = new MemoryStream();
    srcImage.Save(stream, ImageFormat.Png);
    return File(stream.ToArray(), "image/png");
}

The goal in client-side is:

$http.get('/api/GetImage').then(function (response) {
    $("#imgDiv").append('<img src="data:image/png;base64,' + response.data + '" />');
});

The problem I'm having is on line srcImage = Image.FromFile(URL), with error:

An exception of type 'System.IO.FileNotFoundException' occurred in CoreCompat.System.Drawing.dll but was not handled in user code

If it makes any difference, the call to the API URL itself requires a couple seconds to return the Image.

Can anyone advise the proper way to get this accomplished? Or at least help in getting my current approach working?

EDIT - I've looked at How can I convert image url to system.drawing.image for an answer, but it only provides solutions using WebClient which is not available in ASP.Net Core yet.

4

1 回答 1

1

如果要从 URL 读取文件,则需要使用HttpClient

文件控制器.cs

using System;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;

namespace DemoWebCore.Controllers
{
    [Route("api/[controller]")]
    public class FilesController : Controller
    {
        // GET api/files/sample.png
        [HttpGet("{fileName}")]
        public async Task<string> Get(string fileName)
        {
            using (HttpClient client = new HttpClient())
            {
                HttpResponseMessage response = await client.GetAsync(
                     "https://i.stack.imgur.com/hM8Ah.jpg?s=48&g=1");
                byte[] content = await response.Content.ReadAsByteArrayAsync();
                return "data:image/png;base64," + Convert.ToBase64String(content);
            }
        }
    }
}

用法

家庭控制器.cs

using Microsoft.AspNetCore.Mvc;

namespace DemoWebCore.Controllers
{
    public class HomeController : Controller
    {
        public IActionResult Index()
        {
            return View();
        }
    }
} 

看法

<img id="sample-img" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script type="text/javascript">
    $(function () {
        var url = "/api/files/sample.png";
        $.get(url, function (data) {
            console.log(data);
            $("#sample-img").attr('src', data);
        });
    })
</script>

您最初所做的是从文件系统中读取文件。如果该文件位于您的 wwwroot 文件夹中,则此答案可能会对您有所帮助。

于 2017-07-12T14:19:09.893 回答