我正在使用Angular2,TypeScript将文件以及JSON数据发送到服务器。
<input type="file" class="form-control" name="avatar" id="uploadyour" name="uploadyour" #uploadyour="ngModel" [(ngModel)]="model.uploadyour"
(change)="fileChange($event)" placeholder="Upload file" accept=".pdf,.doc,.docx" >
import { Http, Headers, Response, Request, RequestMethod, URLSearchParams, RequestOptions } from "@angular/http";
import * as FileSaver from "file-saver";
import {Observable} from 'rxjs/Rx';
import { Injectable } from '@angular/core';
fileChange(event) {
let fileList: FileList = event.target.files;
if(fileList.length > 0) {
let file: File = fileList[0];
let formData:FormData = new FormData();
console.log(file);
formData.append('uploadFile', file, file.name);
let headers = new Headers();
headers.append('enctype', 'multipart/form-data');
headers.append('Accept', 'application/json');
console.log(headers);
let options = new RequestOptions({ headers: headers });
console.log(formData);
this.http.post("http://localhost:1337/trackstatus/upload", formData, options)
.map(res => res.json())
.catch(error => Observable.throw(error))
.subscribe(
data => console.log('success'),
error => console.log(error)
)
}
}
controller.js
upload: function (req, res) {
req.file('avatar').upload(function (err, files) {
if (err)
return res.serverError(err);
return res.json({
message: files.length + ' file(s) uploaded successfully!',
files: files
});
});
},
我收到以下错误。
XMLHttpRequest无法加载http://localhost:1337/trackstatus/upload。预检响应中的Access-Control-Allow-Headers不允许使用请求标头字段enctype。
答案 0 :(得分:0)
您需要更新服务器上的设置,以允许来自运行Angular代码的域的AJAX请求。如果您的Angular应用程序已在某处发布,则可以是localhost或其他某个域。如何更改CORS设置的细节取决于您的服务器端堆栈,但此SO答案显示了一般修复: