0
asp.net webapiを使用してデータベースに画像を保存しようとしていますか?このコントローラーでは、画像を私の/Content/Banner/
フォルダーに保存しています。asp.net web apiのデータベースに値を渡します
[HttpPost]
[Route("PostBanner")]
[AllowAnonymous]
public HttpResponseMessage PostBannerImage()
{
Dictionary<string, object> dict = new Dictionary<string, object>();
try
{
var httpRequest = HttpContext.Current.Request;
foreach (string file in httpRequest.Files)
{
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created);
var postedFile = httpRequest.Files[file];
if (postedFile != null && postedFile.ContentLength > 0)
{
int MaxContentLength = 1024 * 1024 * 1; //Size = 1 MB
IList<string> AllowedFileExtensions = new List<string> { ".jpg", ".gif", ".png" };
var ext = postedFile.FileName.Substring(postedFile.FileName.LastIndexOf('.'));
var extension = ext.ToLower();
if (!AllowedFileExtensions.Contains(extension))
{
var message = string.Format("Please Upload image of type .jpg,.gif,.png.");
dict.Add("error", message);
return Request.CreateResponse(HttpStatusCode.BadRequest, dict);
}
else if (postedFile.ContentLength > MaxContentLength)
{
var message = string.Format("Please Upload a file upto 1 mb.");
dict.Add("error", message);
return Request.CreateResponse(HttpStatusCode.BadRequest, dict);
}
else
{
var filePath = HttpContext.Current.Server.MapPath("~/Content/Banner/" + postedFile.FileName + extension);
postedFile.SaveAs(filePath);
}
}
var message1 = string.Format("Image Updated Successfully.");
return Request.CreateErrorResponse(HttpStatusCode.Created, message1); ;
}
var res = string.Format("Please Upload a image.");
dict.Add("error", res);
return Request.CreateResponse(HttpStatusCode.NotFound, dict);
}
catch (Exception ex)
{
var res = string.Format("some Message");
dict.Add("error", res);
return Request.CreateResponse(HttpStatusCode.NotFound, dict);
}
}
は、今私はに必要なものこのfilePathににデータベースを送ります。私はちょうどこのファイルパスを次のサービスコントローラーに渡す必要があることを知っています。しかし、私はそれを渡す方法を知らない。誰も私がこの問題を解決するのを助けることができます。
else
{
var filePath = HttpContext.Current.Server.MapPath("~/Content/Banner/" + postedFile.FileName + extension);
postedFile.SaveAs(filePath);
return new HttpResponseMessage()
{
StatusCode = HttpStatusCode.Created,
Content = new StringContent(filePath, Encoding.UTF8, "application/json")
};
}
を今、あなたがファイルパスを持っている:
は、これはこれは
[HttpPost]
[Route("AddBanner")]
public async Task<IHttpActionResult> AddBanner(DisplayBannersDto dto)
{
if (!ModelState.IsValid)
return BadRequest(ModelState);
int? result = await _service.Addbanner(dto);
return Ok();
}
PostBannerImage()APIの内部からイメージパスを保存するか、データベース保存を行うために2番目のAPIを呼び出すかしますか? –
@JoseFrancisデータベースの保存を行うために2番目のAPIを呼び出すようにしたいのですが。 – ManojKanth
PostBannerImage()から "filepath"を返し、クライアントで受信してから、同じものを挿入した後に2番目のAPIを呼び出しますDisplayBannersDto。 –