我在Angular中上传图片时遇到问题。因此,我研究发现了一些您需要删除标题的内容,以便内容类型“边界”将自动出现。在我的有角度的应用程序中,我有拦截器,所以我不需要在每个函数中都附加标头。但是我有一个问题,因为我只想删除onCreateService()函数上的标头,以便保存图像。请在下面检查我的代码。我在REST API和laravel上使用它。
Service.html
onCreateService(form: FormGroup) {
const formData = new FormData();
formData.append('image', this.selectedImage);
formData.append('name', this.servicesForm.get('name').value);
formData.append('amount', this.servicesForm.get('price').value);
formData.append('description', this.servicesForm.get('content').value);
this.servicesService.addService(formData)
.subscribe(
data => {
alert('New service created successfully');
console.log(data);
},
error => {
console.log(error);
alert(`ERROR! can't create new service`);
});
}
Service.ts
addService(formData) {
const headers = new HttpHeaders();
delete headers['Content-Type'];
headers.append('Content-Type', 'multipart/form-data');
return this.httpClient
.post(
this.url, (formData), { headers: headers }
)
.map((response: any) => {
return response;
});
}
Interceptor.ts
export class AuthInterceptor implements HttpInterceptor {
private authService: AuthService;
constructor(private injector: Injector, private router: Router) { }
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
// Get the auth header from the service.
this.authService = this.injector.get(AuthService);
const token = this.authService.getToken();
if (token) {
req = req.clone({ headers: req.headers.set('Authorization', 'Bearer ' + token) });
}
if (!req.headers.has('Content-Type')) {
req = req.clone({ headers: req.headers.set('Content-Type', 'application/json') });
}
req = req.clone({ headers: req.headers.set('Accept', 'application/json') });
return next.handle(req).do(
(event: HttpEvent<any>) => { },
(err: any) => {
if (err instanceof HttpErrorResponse) {
if (err.status === 401 || err.status === 403 || err.status === 400) {
localStorage.clear();
this.authService.logout();
alert('Session has expired!\nYou will be redirected to the login page');
}
}
}
);
}
}
答案 0 :(得分:0)
在拦截器中删除“内容类型”设置器