0
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";

在这里,我想要一些从服务器路径中选择图像并将其转换为二进制流的代码。

变量文件名包含已经保存在服务器中的图像的路径。

此路径引发错误。

我的问题是如何为项目中存储在图像文件夹中的图像获取正确的路径?

               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();
    }
}

}

这是错误的

4

2 回答 2

0

您可以编写自己的函数:

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 stream = new MemoryStream(bytes);

编辑

我不确定您为什么会出错,但是将文件读入二进制数据的版本较短。你可以试试这个吗?

byte[] bytes = System.IO.File.ReadAllBytes("Stuff\\file.exe");
于 2018-05-01T22:54:29.657 回答
0
          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;
于 2018-05-03T18:20:00.990 回答