글을 쓰다가 해결책을 찾았지만 도움이 되실까하여 그대로 올립니다!
현재 이미지를 업로드하고, 그 이미지를 표시하는 기능을 만들고 있습니다.
서버 폴더에 업로드까지는 구현했구요.
문제는 이미지 스트림을 리턴하는 api를 만들었는데, 자꾸만 오류 메시지가 json으로 리턴되네요…
{"type":"https://tools.ietf.org/html/rfc7231#section-6.5.4","title":"Not Found","status":404,"traceId":"00-c18884c8331b08a3ae3e337f4546cddc-0ef7ea279714eac2-00"}
api 컨트롤러 소스는 아래와 같구요.
[Route("api/[controller]")]
[ApiController]
public class ImageController : ControllerBase
{
[HttpGet("[action]")]
public IActionResult GetImage(string name)
{
string imagePath = Path.Combine("./uploads", name);
if (System.IO.File.Exists(imagePath))
{
var fileStream = new FileStream(imagePath, FileMode.Open, FileAccess.Read);
return File(fileStream, "image/jpeg"); // You can specify the appropriate content type here
}
return NotFound();
}
}
호출할 때는 아래와 같이 주소창에서 직접 요청했습니다.
https://localhost:7030/api/image/getimage?name=bf7a9710-3a6c-434b-ae35-d767b8938755.jpg
2 Likes
string imagePath = Path.Combine("./uploads", name);
이 부분에서 슬래시(/)가 문제가 되는 것을 확인했습니다.
imagePath변수값이 /upload\foobar.jpg 이런식으로 되더라고요…
아래와 같이 수정해서 해결되었습니다.
string imagePath = Path.Combine("\\uploads", name);
혹시
return File(fileStream, "image/jpeg");
이 부분에서 jpeg가 아닌 다른 형식(예를 들면 png, gif)도 전부 대응되도록 하는 방법이 있나요?
1 Like
단순히 확장자로만 체크해서 간단하게 처리 하셔도 됩니다.
다음은 간단히
FileExtensionContentTypeProvider 클래스를 사용한 방법의 예시 입니다.
var provider = new Microsoft.AspNetCore.StaticFiles.FileExtensionContentTypeProvider();
string contentType;
provider.TryGetContentType("aaa.png", out contentType); // image/png 반환
provider.TryGetContentType("aaa.gif", out contentType); // image/gif 반환
provider.TryGetContentType("aaa.jpg", out contentType); // image/jpeg 반환
이후에는 질문자님의 코드에서
위에서 반환되는 contentType ← 값을 이용하면 되겠죠?
4 Likes
OS별로 path구분 문자열은 다를 수 있으므로.,
저렇게 path구분 문자를 하드 코딩으로 사용하시는 것 보단
System.IO.Path.DirectorySeparatorChar 정적 변수를 이용해서 사용하시는 것이 좋습니다.
애초에 하드코딩 없이 System.IO.Path.DirectorySeparatorChar를 사용하셨다면 저런 문제는 부딛히지 않으셨을거에요
5 Likes
자료를 더 찾아보니 System.IO.Path.DirectorySeparatorChar를 활용하면
path1 + Path.DirectorySeparatorChar + path2 + Path.DirectorySeparatorChar + …
이런 방식으로 코딩을 해야되더라고요… 상수이름이 길기도 하고
Path.Combine도 운영체제에 맞게 디렉터리 구분자가 자동 생성되니까
그 안에 들어가는 경로문자열에 디렉터리 이름만 들어가도록 수정을 해봤습니다.
string fullPath = Path.Combine(_environment.WebRootPath, "uploads", name);
3 Likes