Asp.net web api 如何在webapi的自定义文件夹中保存字节[]图像?

Asp.net web api 如何在webapi的自定义文件夹中保存字节[]图像?,asp.net-web-api,Asp.net Web Api,我有一个包含图像的模型,我从angularjs发送模型并在webapi中获取模型,我的方法在webapi中 public IHttpActionResult Post([FromBody]Game model) { Image img = LoadImage(model.Image); Game game = model; _repository.Add<Game>(game); return Ok();

我有一个包含图像的模型,我从angularjs发送模型并在webapi中获取模型,我的方法在webapi中

 public IHttpActionResult Post([FromBody]Game model)
    {
        Image img = LoadImage(model.Image);
        Game game = model;
        _repository.Add<Game>(game);
        return Ok();
    }

 public Image LoadImage(string imageName)
    {
        string[] str = imageName.Split(',');
        byte[] bytes = Convert.FromBase64String(str[1]);   
        Image image;
        using (MemoryStream ms = new MemoryStream(bytes))
        {
            image = Image.FromStream(ms);
        }
        return image;
    }
public IHttpActionResult Post([FromBody]游戏模型)
{
图像img=加载图像(model.Image);
游戏=模型;
_添加(游戏);
返回Ok();
}
公共映像加载映像(字符串imageName)
{
字符串[]str=imageName.Split(',');
byte[]bytes=Convert.FromBase64String(str[1]);
图像;
使用(MemoryStream ms=新的MemoryStream(字节))
{
image=image.FromStream(毫秒);
}
返回图像;
}

但这段代码只是将base64返回到image,我想将jpg保存在project的自定义文件夹中

这段代码可以解决您的问题

 public IHttpActionResult Post([FromBody]Game model)
    {
        var image = SaveImage(model.Image, Guid.NewGuid().ToString());
        model.Image = image; // set image name in model            
        _repository.Add<Game>(model);
        return Ok();
    }

   public string SaveImage(string ImgStr, string ImgName)
    {
        String path = HttpContext.Current.Server.MapPath("~/images/Games"); //Path

        //Check if directory exist
        if (!System.IO.Directory.Exists(path))
        {
            System.IO.Directory.CreateDirectory(path); //Create directory if it doesn't exist
        }

        string imageName = ImgName + ".jpg";

        //set the image path
        string imgPath = Path.Combine(path, imageName);


        string[] str = ImgStr.Split(',');
        byte[] bytes = Convert.FromBase64String(str[1]);

        File.WriteAllBytes(imgPath, bytes);

        return imageName;
    }
public IHttpActionResult Post([FromBody]游戏模型)
{
var image=SaveImage(model.image,Guid.NewGuid().ToString());
model.Image=Image;//在模型中设置图像名称
_添加(模型);
返回Ok();
}
公共字符串SaveImage(字符串ImgStr、字符串ImgName)
{
String path=HttpContext.Current.Server.MapPath(“~/images/Games”);//路径
//检查目录是否存在
如果(!System.IO.Directory.Exists(path))
{
System.IO.Directory.CreateDirectory(path);//如果不存在,则创建目录
}
字符串imageName=ImgName+“.jpg”;
//设置图像路径
字符串imgPath=Path.Combine(路径,图像名称);
字符串[]str=ImgStr.Split(',');
byte[]bytes=Convert.FromBase64String(str[1]);
writealBytes(imgPath,字节);
返回图像名称;
}