我想在Angular中上传多张图片,但我仍在上传单张图片,但是现在我最多要上传5张图片。
对于单个图像,我有一个名为attached_image
的参数,用于存储单个图像,但是在这里,我想在optionimage
参数中上传多个图像。
这是我的 component.html
<div class="col-sm-8 col-xs-6">
<div class="file-upload upload-button">
<input id="custom-input" type="file" (change)="handleFiles($event)" multiple>
</div>
<!-- <button type='button' class='btn btn-default' data-toggle="modal" data-target="#imageupload" (click)="resetCropper()">Upload Image</button> -->
<span class="img-selected" *ngIf="isImageselected">
<i class="fa fa-check main-content__checkmark success" id="checkmark"></i>Image sel/span>
</div>
下面的component.ts 代码用于上传单个图像。
handleFiles = function (fileInput: Event) {
this.imageArr = ['image/jpeg', 'image/jpg', image / png','image / gif'];
if (fileInput.target['files'][0]['size'] > 1024000) {
$.growl.error({ title: 'Error', message: "File can not be larger than 1 MB" });
return;
}
if (!this.imageArr.includes(fileInput.target['files'][0]['type'])) {
$.growl.error({ title: 'Error', message: "Invalid file format." });
return;
}
var file: File = fileInput.target['files'][0];
this.extention = file.name.substr((file.name.lastIndexOf('.') + 1)).toLowerCase();
var reader = new FileReader();
reader.onload = this._handleReaderLoaded.bind(this);
reader.readAsBinaryString(fileInput.target['files'][0]);
}
_handleReaderLoaded(readerEvt) {
var binaryString = readerEvt.target.result;
this.base64textString = btoa(binaryString);
this.attached_image = 'data:image/jpeg;base64,' + this.base64textString;
if (this.attached_image) {
this.flashMsg = "Image uploaded successfully!";
}
}
请高度赞赏您的帮助。
答案 0 :(得分:0)
选择多个文件后,您将在fileInput.target['files']
数组中拥有这些文件。您需要遍历并调用validateFile()
。
var files = fileInput.target['files'];
if (files.length > 5)
{
// Error max 5 files
}
for (i=0; i < files.length; i++)
{
validateFile(files[i])
}
...
function validateFile(file) {
if (fileInput.target['files'][0]['size'] > 1024000) {
$.growl.error({ title: 'Error', message: "File can not be larger than 1 MB });
return;
}
if (!this.imageArr.includes(fileInput.target['files'][0]['type'])) {
$.growl.error({ title: 'Error', message: "Invalid file format." });
return;
}
}