Uploading file with other form fields in Angular 2 and Spring MVC

前端 未结 3 1244
逝去的感伤
逝去的感伤 2020-12-30 15:26

I am trying to upload file and other form field contents from my Angular 2 front end to Spring back end. But somehow I am not able to do it. Here is my code

3条回答
  •  既然无缘
    2020-12-30 16:07

    Here is my solution :

    It is very important to leave the Content-Type empty. If you set the 'Content-Type' to 'multipart/form-data' the upload will not work !

    upload.component.html

    
    

    upload.component.ts

      fileChange(event): void {
            const fileList: FileList = event.target.files;
            if (fileList.length > 0) {
                const file = fileList[0];
    
                const formData = new FormData();
                formData.append('file', file, file.name);
    
                const headers = new Headers();
                // It is very important to leave the Content-Type empty
                // do not use headers.append('Content-Type', 'multipart/form-data');
                headers.append('Authorization', 'Bearer ' + 'eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9....');
                const options = new RequestOptions({headers: headers});
    
                this.http.post('https://api.mysite.com/uploadfile', formData, options)
                     .map(res => res.json())
                     .catch(error => Observable.throw(error))
                     .subscribe(
                         data => console.log('success'),
                         error => console.log(error)
                     );
            }
        }
    

提交回复
热议问题