我想通过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);
}