简体   繁体   中英

How to upload image and save using Angular2 and Typescript

i have a image upload section where i need to upload an image. But when i save i get an error saying generic . can anyone help me to solve this.

HTML:

<label >Image</label>
<div >
<input type="file" name="file" id="file" class="inputfile" (change)="readUrlAdd($event)" style="display:none;"/> <label for="file" >Add Image</label>
</div>

Ts:

readUrlAdd(event: any) {
    var files = event.srcElement.files;
    var filename = new Date().getTime() + '.' + files[0].name.split(".")[1];
    var imgFile = new File([files[0]], filename, { type: files[0].type });
    var file_data = imgFile;
    this.ApiService
      .uploadImage(file_data)
      .subscribe(
        image => {
          console.log(image);
          var fileName = image.result.files.file[0].providerResponse.location;
          console.log(fileName);
          this.tutorials = fileName;
        }, error => {
          console.log(error);
        })
  }

API:

uploadImage (files) {
  let token = JSON.parse(localStorage.getItem('token'));
  var fd = new FormData();
  fd.append('file', files);
  return this.http.post(urlBase + '/tutorials/tutorial?token=' + token,fd)
                  .map(this.extractData)
                  .catch(this.handleError);
}

you need to use file uploader for uploading file. for installation use following command. found demo

npm i ng2-file-upload --save

event.srcElement will not work in all browsers, please try the below

const files = event.target.files || event.srcElement.files;
const imgFile = files[0];

You should pass headers with request

let headers = new Headers();
headers.append('token', token); // Try to pass token in header
let options = new RequestOptions({ headers: headers });  

return this.http.post(urlBase + '/tutorials/tutorial,fd, options)
              .map((res: Response) => res.json() || {})
              .catch(this.handleError);

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