简体   繁体   中英

How to call a curl command in Angular using httpClient

I have a curl command which uploads a .zip file to the nexus repository. I want to call this command in Angular. I am wondering how it has to be done. Can you please help me out. command: curl -v -u username:password --upload-file test.zip http://use08nexus01p:8081/nexus/content/repositories/ /

curl's --upload-file parameter uses a PUT request to xfer the data to your server. The -u parameter uses basic authentication. There are a lot of ways you could send a similar request using Angular. You will likely have a service that does this work for you. Below is one possible way to accomplish this. Note that the service function below returns an observable that will need to be subscribed to in a component. Perhaps something like the following:

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { HttpClient, HttpEvent, HttpParams, HttpRequest, HttpHeaders } from '@angular/common/http';

@Injectable({ providedIn: 'root' })
export class AuthService {

    constructor(private http: HttpClient) {}

    public uploadFile(file: File, username: string, password: string): Observable<HttpEvent<any>> {
      // Note - this returns an EVENT, so we can track progress
      var headers = new HttpHeaders();
      headers.append("Authorization", "Basic " + btoa(`${username}:${password}`));
      let formData = new FormData();
      formData.append('upload', file);
      const params = new HttpParams;
      const options = { headers: headers, params: params, reportProgress: true };
      const req = new HttpRequest('PUT', 'http://use08nexus01p:8081/nexus/content/repositories/', formData, options);
      return this.http.request(req);
    }
}

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