Html Angular 2 上传多个文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39608660/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Angular 2 upload multiple files
提问by NNR
I trying to upload multiple files (PDFs or various image formats). Right now uploading a single file works, but multiple does not.
我尝试上传多个文件(PDF 或各种图像格式)。现在上传单个文件有效,但多个文件无效。
This is the code:
这是代码:
HTML:
HTML:
<div>
<label> Upload PDF(s) or Images (PNG/JPG/DICOM/DCM):</label>
<div class="ctrl">
<div class="icon">
<i class="fa fa-file-image-o"></i>
</div>
<input type="file" (change)="onChange($event)"/>
<md-input class="ctrl" [(ngModel)]="fileName"></md-input>
</div>
</div>
Script:
脚本:
onChange(event: any) {
this.fileName = event.srcElement.files[0].name;
}
Help me how to do multiple files upload.
帮助我如何上传多个文件。
回答by mxii
Add the multiple
attribute to you input:
将multiple
属性添加到您的输入:
<input type="file" (change)="onChange($event)" multiple />
And to show all file names in your input, do it like in this plunker: https://plnkr.co/edit/WvkNbwXpAkD14r417cYM?p=preview
并在您的输入中显示所有文件名,请在此 plunker 中执行此操作:https://plnkr.co/edit/WvkNbwXpAkD14r417cYM ?p =preview
import {Component, NgModule} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'
@Component({
selector: 'my-app',
template: `
<div>
<h2>Hello {{name}}</h2>
<input type="file" multiple (change)="onChange($event, showFileNames)" />
<input #showFileNames />
</div>
`,
})
export class App {
constructor() {
this.name = 'Angular2'
}
onChange(event: any, input: any) {
let files = [].slice.call(event.target.files);
input.value = files.map(f => f.name).join(', ');
}
}
@NgModule({
imports: [ BrowserModule ],
declarations: [ App ],
bootstrap: [ App ]
})
export class AppModule {}
Or use your variable instead of putting it directly to that input!
或者使用您的变量而不是直接将其放入该输入!
回答by Atul Bhalerao
回答by Mohd Abdul Baquee
Initialization:
初始化:
selectedFiles: File[];
Files Selection Event :
文件选择事件:
onFileSelected(event) {
this.selectedFiles = event.target.files;
for (let i = 0; i < event.target.files; i++) {
this.selectedFiles.push(event.target.files[i]);
}
}
Form Submission Event :
表单提交事件:
onSubmit() {
const formData = new FormData();
if (this.selectedFiles.length > 0) {
for (const row of this.selectedFiles) {
formData.append('document_files[]', row);
}
}
}
HTML File Input :
HTML 文件输入:
<input
type="file"
id="documents"
multiple
formControlName="documents"
(change)="onFileSelected($event)"
accept="image/*,.pdf,.doc,.docx,.xml">