作者热门文章
- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
angular2 是否支持多部分表单提交,有可用的示例吗?
非常感谢指向特定于此的文档的任何链接
请参阅来自 Angular github 的帖子 https://github.com/angular/angular/issues/6030
任何展示作为 http
的一部分发送 FormData
的示例,
下面是一个对我来说工作正常的代码草案,但想知道 http
<input id="single_f_fileup" [(ngModel)]="model.image" type="file" (change)="selectFile($event)" name="single_fileup" />
selectFile($event): void {
var files = $event.target.files || $event.srcElement.files;
var file = files[0];
let formData = new FormData();
formData.append("single_fileup", file);
formData.append('key1', 'value1');
formData.append('key2', 'value2');
var req = new XMLHttpRequest();
req.open("POST", "/api/fileupload");
req.send(formData);
}
var multer = require('multer');
var storage = multer.memoryStorage();
var upload = multer({ storage: storage });
router.post('/api/fileupload', upload.single('single_fileup'), function(req, res, next){
console.log(req.body,req.file);
});
this.http.post('/api/fileupload', formData)
.map(this.extractData)
.catch(this.handleError);
最佳答案
传递包含图像的 formData 的示例片段
https://gist.github.com/arciisine/ee57727e56cbc5e83739b2c24fd69658
https://github.com/angular/angular/issues/6030
import { Component, Input, AfterViewInit } from '@angular/core';
import { NgModel, DefaultValueAccessor, NgControl } from '@angular/forms';
import { Http, Headers, RequestOptions } from '@angular/http';
@Component({
selector: 'app-file-uploader',
template: '<input type="file" (change)="updated($event);">',
providers: [NgModel, DefaultValueAccessor]
})
export class FileUploaderComponent implements AfterViewInit {
static ROOT = '/rest/asset';
@Input() private companyId: string = '';
private value: string;
private changeListener: Function;
constructor(private http: Http, private input: NgControl) {
this.input.valueAccessor = this;
}
ngAfterViewInit() {
}
writeValue(obj: any): void {
this.value = obj;
}
registerOnChange(fn: any): void {
this.changeListener = fn;
}
registerOnTouched(fn: any): void {
}
updated($event) {
const files = $event.target.files || $event.srcElement.files;
const file = files[0];
const formData = new FormData();
formData.append('file', file);
const headers = new Headers({});
let options = new RequestOptions({ headers });
let url = FileUploaderComponent.ROOT + (this.companyId ? '/' + this.companyId : '');
this.http.post(url, formData, options).subscribe(res => {
let body = res.json();
this.value = body.filename;
if (this.changeListener) {
this.changeListener(this.value);
}
});
}
}
关于angular - 如何使用angularjs2上传文件(多部分),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39731066/
我有以下正则表达式 /[a-zA-Z0-9_-]/ 当字符串只包含从 a 到z 大小写、数字、_ 和 -。 我的代码有什么问题? 能否请您向我提供一个简短的解释和有关如何修复它的代码示例? //var
我是一名优秀的程序员,十分优秀!