简体   繁体   中英

Upload Image file and send to rest API

 import { Component } from '@angular/core'; import { Http, RequestOptions, Headers, Response } from '@angular/http'; import { Observable } from 'rxjs/Rx'; @Component({ selector: 'my-app', templateUrl: './app/app.component.html', styleUrls: ['./app/styles/styles.css'] }) export class AppComponent { private isUploadBtn: boolean = true; constructor(private http: Http) { } //file upload event fileChange(event) { debugger; let fileList: FileList = event.target.files; if (fileList.length > 0) { let file: File = fileList[0]; let formData: FormData = new FormData(); formData.append('uploadFile', file, file.name); let headers = new Headers() headers.append('Content-Type', 'json'); headers.append('Accept', 'application/json'); let options = new RequestOptions({ headers: headers }); let apiUrl1 = "/api/UploadFileApi"; this.http.post(apiUrl1, formData, options) .map(res => res.json()) .catch(error => Observable.throw(error)) .subscribe( data => console.log('success'), error => console.log(error) ) } window.location.reload(); } } 
 <div class="fileUpload btn btn-primary" *ngIf="isUploadBtn"> <span>Upload</span> <input type="file" id="btnUpload" value="Upload" (change)="fileChange($event)" class="upload" /> </div> 

I have implemented the above code, which is handled by a Django REST API. But it shows 415 status code that is Unsupported media type...!

While when I send the same request through POSTMAN it accepts. Postman Curl command is

curl -X POST \
     http://192.168.1.223:8010/profilepic/ \
     -H 'authorization: Basic OTc5Nzk3OTc5NzoxMjM=' \
     -H 'cache-control: no-cache' \
     -H 'content-type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW' \
     -H 'postman-token: 0e6c2353-5a24-2223-d4f3-b8d74c334a3d' \
     -F datafile=@/home/ashwini/Pictures/step4.png

My curl command is

curl 'http://192.168.1.223:8010/profilepic/' \
     -H 'Origin: http://192.168.1.144:4200' \
     -H 'Accept-Encoding: gzip, deflate' \
     -H 'Accept-Language: en-GB,en-US;q=0.8,en;q=0.6' \
     -H 'User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36' \
     -H 'Content-Type: multipart/form-data; boundary=AaB03x' \
     -H 'Accept: application/json, text/plain, */*' \
     -H 'Referer: http://192.168.1.144:4200/' \
     -H 'Connection: keep-alive' \
     --data-binary 'datafile=@/home/ashwini/Pictures/step4.png' \
     --compressed

curl命令和JS调用的内容类型不同。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM