我在用什么
- Angular
- 火力基地
我要实现的目标
上传项目详细信息时,我想知道是否已选择图片。
如果不是,则从服务调用不同的方法并分配默认图像
如果是,使用图片
问题
我可能处理这个错误,但我考虑执行此逻辑的方式是查看用户是否选择了“选择图像”(类型文件的输入)。如果已选择图像,则“if(文件)”似乎可以正常注册,如果未选择图像,则会出现以下错误:
ProjectsAddComponent.html:71 ERROR TypeError: Cannot read property 'item' of undefined
- 如何检测用户是否选择了要与数据一起上传的图像?
项目添加 HTML
<div class="vs__upload__container">
<input type="file" id="file-1" class="inputfile inputfile-1" (change)="detectFiles($event)" />
<label class="vs__upload__button" for="file-1">
<i class="fa fa-upload" aria-hidden="true"></i>
<span>Choose a file…</span>
</label>
</div>
<div class="vs__details__actions">
<button class="vs__button" (click)="addNewProject(newTitle.value, newReference.value, newDate.value); newTitle.value='';
newReference.value=''; newDate.value='';">
Add
</button>
</div>
项目添加组件TS
请引用'addNewProject'函数if语句
import { Component, OnInit } from '@angular/core';
import { ProjectsAddService } from './projects-add.service';
import { Upload } from './upload';
import * as _ from "lodash";
@Component({
selector: 'upload-form',
templateUrl: './projects-add.component.html',
styleUrls: ['./projects-add.component.css']
})
export class ProjectsAddComponent {
selectedFiles: FileList;
currentUpload: Upload;
constructor(private upSvc: ProjectsAddService) { }
detectFiles(event) {
this.selectedFiles = event.target.files;
}
uploadSingle() {
let file = this.selectedFiles.item(0)
this.currentUpload = new Upload(file);
}
addNewProject(title: string, reference: string, date: string) {
let file = this.selectedFiles.item(0)
this.currentUpload = new Upload(file);
if (file) {
console.log('this is the file = ', file);
// Call method in service to include the upload file
this.upSvc.addNewProjectWithImage(title, reference, date, this.currentUpload);
} else {
console.log('no file');
this.upSvc.addNewProjectWithOutImage(title, reference, date);
}
}
}
最佳答案
您需要检查是否选择了任何文件。您的代码可能抛出未定义的异常。
addNewProject(title: string, reference: string, date: string)
{
// Check if an image file has been selected
if(this.selectedFiles && this.selectedFiles.length > 0) {
let file = this.selectedFiles.item(0);
this.currentUpload = new Upload(file);
console.log('this is the file = ', file);
// Call method in service to include the upload file
this.upSvc.addNewProjectWithImage(title, reference, date, this.currentUpload);
}
// otherwise call the method with default image.
else {
console.log('no file');
this.upSvc.addNewProjectWithOutImage(title, reference, date);
}
}
检查 uploadSingle
方法中的相同条件。
uploadSingle() {
if(this.selectedFiles && this.selectedFiles.length > 0) {
let file = this.selectedFiles.item(0);
this.currentUpload = new Upload(file);
}
}
关于javascript - 如何检测 Angular 中是否填充了文件输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45691047/