我正在尝试以角度2上传图片,我没有列出错误,但文件添加详细代码的位置没有变化,如下所示
**.ts**
............
onFileChange(event) {
if(event.target.files.length > 0) {
let file = event.target.files[0];
this.fileName = file.name;
this.imageUpload['upload'] = this.fileName;
this.form.get('upload').setValue(file);
console.log(file);
console.log('filename',this.fileName);
}
}
private prepareSave(): any {
let inputVal = new FormData();
inputVal.append('upload', this.form.get('upload').value,this.imageUpload['upload']);
console.log(inputVal);
return inputVal;
}
onSubmit() {
this.imageUpload['upload'] = this.fileName;
const formModel = this.prepareSave();
this.loading = true;
var body = formModel;
let url = this.ImageUploadURL;
let headers = new Headers({ 'Content-Type': 'multipart/form-data' ,'Authorization': 'Bearer ' + this.accountsService.accessToken });
let options = new RequestOptions({ headers: headers });
console.log(options);
console.log(body);
console.log(url);
// In a real-world app you'd have a http request / service call here like
return this.http.post(url, body, options)
.catch(error => Observable.throw(error))
.subscribe(
data => console.log('success'),
error => console.log(error)
)
}
...............
该方法是使用url和 的 { 上传:"" }
可能是所需部分没有变化的错误?
还有其他方法吗?
答案 0 :(得分:5)
在Angular中,当使用多部分表单数据并且您正在使用FormData对象时,您不能指定Content-Type标头。
通过这样做,您阻止http堆栈将其设置为MUST include the boundary value的正确值。
只需删除内容类型标题,让格式化程序为您处理,您应该没问题。
答案 1 :(得分:1)
表单编码必须为multipart/form-data
而不是form-data
。
尝试此更改:
let headers = new Headers();
headers.set('Content-Type', 'multipart/form-data');
headers.set('Authorization', 'Bearer' + blah);
如果要重构组件,有一种稍微不同的方法:
https://gist.github.com/arciisine/ee57727e56cbc5e83739b2c24fd69658