如何在Asp Web Api 2中保存Byte数组中的图像?

时间:2017-01-01 23:32:24

标签: asp.net asp.net-web-api http-post httpclient image-uploading

我想通过BsonMediaTypeFormatter将Image对象传递给web api,以便在服务器上保存图像,并在数据库中保存图像URL。

我已经完成了以下代码,但效果不佳。在Bitmap btmap = new Bitmap(ms);

中休息

上传对象:

public class UploadCategoryDTO
{

    public string CategoryTitle { get; set; }

    public byte[] Picture { get; set; }

    public DateTime Date { get; set; }
}

和后期行动:

 [ResponseType(typeof(UploadCategoryDTO))]
    public IHttpActionResult PostCategoryModel(UploadCategoryDTO categoryUploadModel)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        CategoryModel categoryModel = new CategoryModel();
        categoryModel.CategoryTitle = categoryUploadModel.CategoryTitle;
        categoryModel.Date = categoryUploadModel.Date;
        var folderName = "Picture";
        string filename = folderName + "/" + categoryUploadModel.CategoryTitle + ".png";
        var PATH = HttpContext.Current.Server.MapPath("~/" + filename);
        using (MemoryStream ms = new MemoryStream(categoryUploadModel.Picture))
        {
            Bitmap btmap = new Bitmap(ms);
            btmap.Save(PATH, System.Drawing.Imaging.ImageFormat.Png);
        }
        string baseuri = "http://localhost:13566/";

        categoryModel.PictureUri = baseuri + filename;
        db.CategoryModels.Add(categoryModel);
        db.SaveChanges();

        return CreatedAtRoute("DefaultApi", new { id = categoryModel.ID }, categoryModel);
    }

0 个答案:

没有答案