хотите выбрать изображение из пути к серверу и преобразовать его в двоичную форму - PullRequest
0 голосов
/ 02 мая 2018
public class AdminController : Controller
   {
       public HHCCEntities hc = new HHCCEntities();
       public ActionResult ServicesView()
    {
        var x = hc.Services.ToList();
        return View(x);
    }
    [Authorize]
    public ActionResult AddServices(int id = 0)
    {

        if (id == 0)
        {
            return View(new Service());
        }
        else
        {
            Service s = new Service();
            HttpResponseMessage response = 
GlobalVariables.webapiclient.GetAsync("Services/" + id.ToString()).Result;
            s = response.Content.ReadAsAsync<Service>().Result;
            return View(s);

        }

    }
     private byte[] GetBinaryFile(string filename)
    {
        byte[] bytes;
        using (FileStream file = new FileStream(filename, FileMode.Open, FileAccess.Read))
        {
            bytes = new byte[file.Length];
            file.Read(bytes, 0, (int)file.Length);
        }
        return bytes;
    }
    [Authorize]
    [HttpPost]
    public ActionResult AddServices(Service s, HttpPostedFileBase ImageFile)
    {
        if (ImageFile != null)
        {
            s.Simage = new byte[ImageFile.ContentLength];
            ImageFile.InputStream.Read(s.Simage, 0, ImageFile.ContentLength);
        }
        if (s.ID==0)
        {
            if (ImageFile == null)
            {

                string filename = "MVC_WEBAPI\\images\\patient.png";

здесь я хочу некоторый код, который выбирает изображение из пути сервера и преобразует его в двоичный поток.

Переменная filename содержит путь к изображению, которое уже сохранено на сервере.

Этот путь выдает ошибку.

Мой вопрос: как правильно выбрать правильный путь для изображения, которое хранится в папке изображений в проекте?

               byte[] bytes = GetBinaryFile(filename);

            }
            HttpResponseMessage response = GlobalVariables.webapiclient.PostAsJsonAsync("Services", s).Result;
        }
        else
        {
            HttpResponseMessage response = GlobalVariables.webapiclient.PutAsJsonAsync("Services/" + s.ID, s).Result;
        }
        return View();
    }
}

}

This in error

Ответы [ 2 ]

0 голосов
/ 03 мая 2018
          if (ImageFile == null)
               {  
                string filename = "/images/Services.png";
                var dir = Server.MapPath(filename);
                byte[] bytes = System.IO.File.ReadAllBytes(dir);
                s.Simage = bytes;
               }
    HttpResponseMessage response = 
GlobalVariables.webapiclient.PostAsJsonAsync("Services", s).Result;
0 голосов
/ 02 мая 2018

Вы можете написать свою собственную функцию:

private byte[] GetBinaryFile(filename)
{
     byte[] bytes;
     using (FileStream file = new FileStream(filename, FileMode.Open, FileAccess.Read))
     {
          bytes = new byte[file.Length];
          file.Read(bytes, 0, (int)file.Length);
     }
     return bytes;
}

Затем вы можете вызвать эту функцию из действия вашего контроллера:

byte[] bytes = GetBinaryFile("filename.bin");

Вы также можете выбросить его в поток:

Stream stream = new MemoryStream(bytes);

EDIT

Я не уверен, почему вы получаете ошибку, но существует более короткая версия чтения файла в двоичные данные. Вы можете попробовать это?

byte[] bytes = System.IO.File.ReadAllBytes("Stuff\\file.exe");
...