簡體   English   中英

如何更改Angular5的內容類型-HTTP RequestOptions HEADERS

[英]How to Change the Content-Type of Angular5 - HTTP RequestOptions HEADERS

我正在嘗試通過Angular 5將圖像發送到Node我遇到的問題是,當我嘗試它時,Angular發送一個空的Json文件

這是HTML5代碼:

<input (change)="onFileSelected($event)" type="file" class="custom-file-input" name="file" id="file" accept="image/gif, image/jpg,  image/jpeg" >
<button type="button" (click)="onUpload()" class="btn btn-info btn-block">upload</button>

這是component.ts中的代碼

onFileSelected(event){
  this.selectedFile = event.target.files[0];
  console.log(event);
}
onUpload(){
  const fd = new FormData();
  fd.append('file',this.selectedFile, this.selectedFile.name);
  this.authService.onUpload(fd).subscribe(data=>{
    if(!data.success){
      this.messageClass = 'alert alert-danger'; // Set bootstrap error class
      this.message = data.message; // Set error message
      console.log(data.message);
    }else{
      this.messageClass = 'alert alert-success'; // Set bootstrap error class
      this.message = data.message; // Set error message
      console.log('it worked');
    }
  });

}

當我上傳沒有標題的文件並消除后端檢查器時,它可以工作,但是我需要對請求的某種授權,因此需要令牌文件

令牌創建的代碼

// Function to create headers, add token, to be used in HTTP requests
  createAuthenticationHeaders() {
    this.loadToken(); // Get token so it can be attached to headers
    // Headers configuration options
    this.options = new RequestOptions({
      headers: new Headers({
        'Content-Type': 'application/json', // Format set to JSON
        'authorization': this.authToken // Attach token
      })
    });
  }

loadToken() {
  this.authToken = localStorage.getItem('token'); // Get token and asssign to variable to be used elsewhere
}

服務代碼

// Function to get user's upload image
  onUpload(fd){
    this.createAuthenticationHeaders(); // Create headers before sending to API
    return this.http.post(this.domain + '/authentication/profileImage',fd , this.options).map(res => res.json());
  }

因此,現在每當我發出請求時,都將其提交給Json,如何將其作為文件類型發送

我創建一個新函數並更改了Content-Type

createAuthenticationHeadersForFiles() {
    this.loadToken(); // Get token so it can be attached to headers
    // Headers configuration options
    this.option = new RequestOptions({
      headers: new Headers({
        'Content-Type': 'application/form-data', // Format set to FormData
        'authorization': this.authToken // Attach token
      })
    });
  }

  // Function to get token from client local storage
loadToken() {
  this.authToken = localStorage.getItem('token'); // Get token and asssign to variable to be used elsewhere
} 

但是它沒有按預期工作,無法保存圖像

使用Node的后端代碼

/* ===============================================================
     Route to post user's profile image
  =============================================================== */
  // init gfs
  let gfs;
  const conn = mongoose.createConnection('mongodb://localhost:27017/zaad');
  conn.once('open',()=>{
    gfs = Grid(conn.db,mongoose.mongo);
    gfs.collection('profileImages');
  });

  const storage = new GridFsStorage({
    url:config.uri,
    file:(req,file)=>{
      return new Promise((resolve,reject)=>{
        crypto.randomBytes(16,(err,buf)=>{
          if(err){
            return reject(err);
          }
          const filename = buf.toString('hex')+ path.extname(file.originalname);
          const fileinfo = {
            filename:filename,
            bucketName:'profileImages'
          };
          resolve(fileinfo);
        });
      });
    }
  });

  const upload = multer({storage});
  router.post('/profileImage',upload.single('file'),(req,res)=>{
    if(!req.file){
      res.json({success:false , message:'no image was provided'});
    }else{

      res.json({file:req.file});
    }
  });

然后,使用Chrome中的devtool,我嘗試分析請求和結果

General:
Request URL: http://localhost:8080/authentication/profileImage
Request Method: POST
Status Code: 200 OK
Remote Address: [::1]:8080
Referrer Policy: no-referrer-when-downgrade
Response Headers:
Access-Control-Allow-Origin: http://localhost:4200
Connection: keep-alive
Content-Length: 51
Content-Type: application/json; charset=utf-8
Date: Sat, 26 May 2018 11:17:16 GMT
ETag: W/"33-cBZTT/RGV75GPZIbsrhHP7Mg3SM"
Vary: Origin
X-Powered-By: Express
Request Headers:
Accept: application/json, text/plain, */*
Accept-Encoding: gzip, deflate, br
Accept-Language: ar,en-US;q=0.9,en;q=0.8,fr;q=0.7
authorization: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiI1YWYzZDM4ZWE1MWM0ZjMxNzhlYWFkN2QiLCJpYXQiOjE1MjczMzI3NzksImV4cCI6MTUyNzQxOTE3OX0.78SoKSz5KlIQB-sh3oZjrfiot9cFLUuH79Q-DgRmSag
Connection: keep-alive
Content-Length: 763935
Content-Type: application/form-data
Host: localhost:8080
Origin: http://localhost:4200
Referer: http://localhost:4200/edit-profile/5af3d38ea51c4f3178eaad7d
User-Agent: Mozilla/5.0 (Windows NT 6.2; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36
Request Payload:
------WebKitFormBoundaryUq12HhowsrOlY9bF
Content-Disposition: form-data; name="file"; filename="erp-img.jpg"
Content-Type: image/jpeg


------WebKitFormBoundaryUq12HhowsrOlY9bF--

問題似乎出在“ createAuthenticationHeaders() ”函數中。 在此函數中,您將Content-Type設置為“ application / json ”,而不是將其設置為“ multipart / form-data ”或“ application / form-data ”(以適合您的方式為准),以便更新的createAuthenticationHeaders()方法將是:-

  createAuthenticationHeaders() {
    this.loadToken(); // Get token so it can be attached to headers
    // Headers configuration options
    this.options = new RequestOptions({
      headers: new Headers({
        'Content-Type': 'application/form-data', // or any other appropriate type as per requirement
        'authorization': this.authToken // Attach token
      })
    });
  }

- - - - - - - - - - - - - - -編輯 - - - - - - - - - - ----

由於您的請求有效負載顯示為:-

    ------WebKitFormBoundaryUq12HhowsrOlY9bF
Content-Disposition: form-data; name="file"; filename="erp-img.jpg"
Content-Type: image/jpeg

這意味着客戶端工作正常。 問題出在服務器端。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM