【发布时间】:2019-07-30 03:57:35
【问题描述】:
我正在将图像从上传器保存到数据库中,所以它对我来说非常适合,但问题是我是否想在我的网站上显示该图像,那么我该如何显示它们,并且图像路径应该显示为 src="http://www.example.com/image.png"。
请给我任何示例/解决方案。
TS
imageUrl: string = "/assets/img/default-image.png";
fileToUpload: File = null;
constructor(private imageService: ImageUploadService) { }
handleInputFile(file: FileList){
this.fileToUpload = file.item(0);
var reader = new FileReader();
reader.onload = (event:any) => {
this.imageUrl = event.target.result;
}
reader.readAsDataURL(this.fileToUpload);
}
OnSubmit(Caption,Image){
this.imageService.postFile(Caption.value, this.fileToUpload).subscribe(
data => {
console.log("Done");
Caption.value = "";
Image.value = "";
}
);
}
Service.Ts
postFile(caption: string, fileToUpload: File){
const endpoint = 'http://localhost:3343/api/UploadImage';
const formData: FormData = new FormData();
formData.append("Image", fileToUpload, fileToUpload.name);
formData.append("Caption", caption);
return this.http.post(endpoint,formData);
}
HTML
<form #imageForm="ngForm" (ngSubmit)="OnSubmit(Caption,Image)">
<div class="input-field col s12">
<input type="text" #Caption ngModel name="Caption" id="Caption">
<label for="Caption">Caption</label>
</div>
<img [src]="imageUrl" style="width:200px;height:200px;">
<input type="file" #Image accept="Image/*" (change)="handleInputFile($event.target.files)">
<button class="btn waves-effect waves-light" type="submit">Submit
<i class="material-icons right">send</i>
</button>
</form>
【问题讨论】:
-
我在回答中做了一个demo,你可以看看
标签: angular typescript asp.net-web-api file-upload angular6