我正在从WebApi中的文件夹中获取图像,并尝试在我的角度应用程序中呈现它。这是从文件夹中获取图像的Web服务代码:
[HttpGet]
[Route("GetProfileImage")]
[Authorize]
public IActionResult GetImage()
{
try
{
var userId = User.Claims.First(c => c.Type == "UserID").Value;
var photo = _applicationContext.files.FirstOrDefault(x => x.UserId == userId);
var fileName = photo.FileName;
var uploadFilesPath = Path.Combine(_iHostingEnvironment.ContentRootPath, "uploads");
var filePath = Path.Combine(uploadFilesPath, fileName);
return Ok(PhysicalFile(filePath, "image/jpeg"));
}
catch (Exception ex)
{
return BadRequest(ex.Message);
}
}
这是后端中调用webapi的代码:
component.ts
getProfileImage() {
this.userService.getProfileImage()
.subscribe((data: any) => {
this.imageUrl = data.fileName;
console.log(data.fileName);
});
}
service.ts
public getProfileImage = () => {
return this.http.get(this.baseUrl + '/api/ApplicationUser/GetProfileImage');
}
component.html
<div class="card-avatar" *ngIf="imageUrl">
<a href="javascript:void(0)" >
<img class="img" src="imageUrl" />
</a>
</div>
在console.log答复中,我会像这样获取文件本身的物理位置:
D:\ backend \ uploads \ ca897a19-d8f6-4f77-8445-927c29f9f86d.jpg
但它未在.html文件的src中呈现。
能否请您教我正确的做法。谢谢。
答案 0 :(得分:1)
尝试这样:
<img class="img" [src]="imageUrl" />
或
<img class="img" src="{{imageUrl}}" />
答案 1 :(得分:1)
让动作在调用时返回原始图像数据
//GET api/ApplicationUser/ProfileImage
[HttpGet("ProfileImage")]
[Authorize]
public IActionResult GetImage() {
try {
var userId = User.Claims.First(c => c.Type == "UserID").Value;
var photo = _applicationContext.files.FirstOrDefault(x => x.UserId == userId);
if(photo == null) return NotFound();
var fileName = photo.FileName;
var uploadFilesPath = Path.Combine(_iHostingEnvironment.ContentRootPath, "uploads");
var filePath = Path.Combine(uploadFilesPath, fileName);
if(!System.IO.File.Exists(filePath)) return NotFound();
return File(filePath, profile.jpg, "image/jpeg"));
} catch (Exception ex) {
return BadRequest(ex.Message);
}
}
只需让组件使用其路线/ URL调用操作即可。
component.ts
getProfileImage() {
this.imageUrl = this.userService.getProfileImage();
console.log(this.imageUrl);
}
service.ts
public getProfileImage = () => {
return this.baseUrl + '/api/ApplicationUser/ProfileImage';
}
component.html
<div class="card-avatar" *ngIf="imageUrl">
<a href="javascript:void(0)" >
<img class="img" src="{{imageUrl}}" />
</a>
</div>
浏览器应按照解析解析img.src
路径时的设计处理图像的实际下载和渲染。
答案 2 :(得分:0)
component.html
<div class="card-avatar" *ngIf="imageUrl">
<a href="javascript:void(0)" >
<img class="img" src="{{imageUrl}}" />
</a>
</div>
答案 3 :(得分:0)
您始终可以在Base64上转换图像并将其嵌入html上。为了方便阅读,您可以看到 ngx-网络摄像头
答案 4 :(得分:0)
尝试仅返回图像路径,而不返回物理路径。
return Ok(filePath);
然后像这样变红
<img class="img" [src]="imageUrl" />
或
<img class="img" src="{{imageUrl}}" />