File Upload In Angular?

前端 未结 14 2580
执念已碎
执念已碎 2020-11-22 08:10

I know this is very a general question but I am failing to upload a file in Angular 2. I have tried

1) http://valor-software.com/ng2-file-upload/ and

2) h

14条回答
  •  南方客
    南方客 (楼主)
    2020-11-22 08:59

    In Angular 2+, 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

    export class UploadComponent implements OnInit {
        constructor(public http: Http) {}
    
        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)
                     );
            }
        }
    }
    

提交回复
热议问题