asp mvc에서 데이터베이스의 이미지 표시
컨트롤러에서 바이트 배열 형식의 이미지를 받고 있는데, 어떻게 이것을 뷰에 표시 할 수 있습니까? 가장 간단한 방법으로.
데이터베이스에서 표시 할 이미지의 ID를 사용하는 Show 작업으로 이미지를 표시하기위한 컨트롤러를 만듭니다. 작업은 적절한 콘텐츠 유형의 이미지 데이터가 포함 된 FileResult를 반환해야합니다.
public class ImageController : Controller
{
public ActionResult Show( int id )
{
var imageData = ...get bytes from database...
return File( imageData, "image/jpg" );
}
}
보기에서 이미지를 구성하고 이미지 ID를 사용하여 컨트롤러 및 작업을 사용하여 이미지의 경로를 구성합니다.
<img src='<%= Url.Action( "show", "image", new { id = ViewData["imageID"] } ) %>' />
이것을 사용하는 데 허용되는 대답 :
<img src='<%= Url.Action( "show", "image", new { id = ViewData["imageID"] } ) %>'
괜찮지 만 mvc 4에서는 구식입니다. 이제 업데이트 된 구문은 다음과 같습니다.
<img src='@Url.Action( "show", "image", new { id = ViewData["imageID"] })' />
또한이 기능이 필요할 때 이미 다른 데이터를 뷰에 전달하고 있으므로 ViewData 대신 Model을 사용하는 것이 좋습니다.
public class MyModel {
public string SomeData {get;set;}
public int FileId {get; set;}
}
컨트롤러에서 :
public ActionResult Index() {
MyEntity entity = fetchEntity();
MyModel model = new MyModel {
SomeData = entity.Data,
FileId = entity.SomeFile.ID
};
return View(model);
}
마지막으로 귀하의 관점에서 :
<img src='@Url.Action("show", "image", new { id = Model.FileId })' />
수락 된 답변에 대한 컨트롤러의 "Show"메서드는 작동하지만 File.ContentType을 사용하도록 하드 코딩 된 "image / jpg"를 변경합니다. byte []와 함께 저장할 수 있으므로 추측 할 필요가 없습니다. 사용자가 자신의 이미지를 업로드하고 있습니다.
나는이 게시물이 다소 오래되었다는 것을 알고 있지만 대부분의 Augi 답변에 대해 이것을 수행하는 방법을 알아 내려고 할 때 처음 나온 것 중 하나 였지만 대부분의 어셈블리는 구식입니다.
나는 mvc2 미리보기를 다운로드 1
microsoft.web.mvc 항목에 대해 걱정할 필요가 없습니다. 어쨌든 그 항목을 찾을 수 없었고 그것이 무엇으로 발전했는지 알아 내려고 약 한 시간 동안 검색합니다.
이것은 이미지 유형의 db 필드에서 이미지를 표시하기 위해 저를 위해 작성한 코드입니다.
내가 저장소라고 부르는 컨트롤러 클래스에서 나는 이것을 가지고있다.
public ActionResult GetImage(int id)
{
byte[] imageData = storeRepository.ReturnImage(id);
//instead of what augi wrote using the binarystreamresult this was the closest thing i found so i am assuming that this is what it evolved into
return new FileStreamResult(new System.IO.MemoryStream(imageData), "image/jpeg");
}
//in my repository class where i have all the methods for accessing data i have this
public byte[] ReturnImage(int id)
{
// i tried his way of selecting the right record and preforming the toArray method in the return statment
// but it kept giving me an error about converting linq.binary to byte[] tried a cast that didnt work so i came up with this
byte[] imageData = GetProduct(id).ProductImage.ToArray();
return imageData;
}
now for my view page i tried al kinds of ways i found in these forms and nothing worked i am assuming they were just outdated so i tried on a whim the simplest of all thing i could think of and it worked perfectly
<image src='/store/getimage/<%= Html.Encode(Model.productID) %>' alt="" />
i kept getting an error from the site about posting img tags so make sure you change the above image to img
hope that helps stop anyone from hunting all day for a current answer
http://aspnet.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=30886
public ActionResult EmployeeImage(int id)
{
byte[] imageData ="Retrieve your Byte[] data from database";
if (imageData!= null && imageData.Length > 0)
{
return new FileStreamResult(new System.IO.MemoryStream(imageData), "image/jpeg");
}
}
Every answer here may be correct but the simplest way from my opinion is get byte array or Model containing image and simply add like this
<img src="data:image/jpeg;base64,@(Convert.ToBase64String(Model.Picture))">
Assuming you have a dataRow (dr) with two columns, "name" and "binary_image" (binary_image contains the binary info)
Byte[] bytes = (Byte[])dr["Data"];
Response.Buffer = true;
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = dr["Image/JPEG"].ToString();
Response.AddHeader("content-disposition", "attachment;filename=" & dt.Rows[0]["Name"].ToString());
Response.BinaryWrite(bytes);
Response.Flush();
Response.End();
참고URL : https://stackoverflow.com/questions/880515/display-image-from-database-in-asp-mvc
'development' 카테고리의 다른 글
'EventTarget'유형에 'value'속성이 없습니다. (0) | 2020.11.30 |
---|---|
한 컴퓨터의 모든 코어를 사용하는 Pandas Dataframes에서 apply ()를 어떻게 병렬화합니까? (0) | 2020.11.30 |
C #을 사용하여 Excel에서 셀 색상 변경 (0) | 2020.11.30 |
GROUP BY-NULL을 그룹화하지 않음 (0) | 2020.11.30 |
Eclipse의 검색 결과에서 대상 폴더 제외 (0) | 2020.11.30 |