您好,我想通过 Angular to Net Core 2.1 API 上传文件。
在我的前端项目中,我为令牌认证配置了一个全局拦截器。
身份验证可以很好地与其他调用配合使用,但是当我尝试过帐FormData并附加身份验证头时,服务器将发送“缺少内容类型边界”错误。而且当我不附加任何标题时,它将正常工作。
您能看到我在做什么吗?
这是我的拦截器:
@Injectable({ providedIn: 'root' })
export class AuthInterceptor implements HttpInterceptor {
constructor() { }
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const userData: string = localStorage.getItem('userData');
let request = req;
if (userData != null) {
const user = JSON.parse(userData);
request = request.clone({
setHeaders: {
Authorization: `Bearer ${user['_token']}`
}
});
}
return next.handle(request);
}
}
这是我的组件:
export interface Contract {
id: number;
title: string;
document?: File;
}
@Component({
selector: 'app-contract',
templateUrl: './contract.component.html'
})
export class ContractComponent implements OnInit {
contractForm: FormGroup;
constructor(
private api: ContractService
) { }
ngOnInit() {
this.contractForm = new FormGroup({
id: new FormControl(0),
title: new FormControl(null, [Validators.required]),
document: new FormControl(null, [Validators.required])
});
}
onAddContract() {
const formData = new FormData();
formData.append('id', '0');
formData.append('title', this.contractForm.get('title').value);
formData.append('document', this.contractForm.get('document').value, this.contractForm.get('title').value);
this.api.postContract(formData).subscribe(result => {
});
}
handleFileInput(event) {
if (event.target.files.length > 0) {
const file = event.target.files[0];
this.contractForm.get('document').setValue(file);
}
}
}
这是我的服务:
@Injectable({ providedIn: 'root' })
export class ContractService {
API_URL: string = "http://localhost:59976/api"
constructor(private http: HttpClient) { }
postContract(contract: FormData) {
const httpOptions = {
headers: new HttpHeaders({
'Content-Type' : 'multipart/form-data'
})
};
return this.http.post<Contract>(this.API_URL + '/contratos', contract);
}
}
我举了一个小例子: