简体   繁体   English

如何在 ng2-file-upload 中添加自定义标题

[英]How to add Custom Headers in ng2-file-upload

I'm experimenting with ng2-file-upload, the problem is I can't set the custom headers.我正在试验 ng2-file-upload,问题是我无法设置自定义标头。 So far I've done this到目前为止我已经这样做了

In the upload-documents.componentupload-documents.component 中

  import { Component } from '@angular/core';
  import { FileUploader,  Headers } from 'ng2-file-upload';

  @Component({
      moduleId: module.id,
      selector: 'sg-uploadcompnent',
      templateUrl: '../views/upload-documents.template.html'
  })

  export class UploadDocumentsComponent {
     public uploader: FileUploader = new FileUploader({
     url: "http://localhost:port/app/api/upload/",
     authToken: "Authorization",
     authTokenHeader: "Bearer mytoken871lkdk39829",
     isHTML5: true,
     **headers: [
         {name: "myCustomHeader", value:"some value"}]**
  });
}

In the upload-documents.template.html上传文档.template.html

    <style>
.my-drop-zone { border: dotted 3px lightgray; }
.nv-file-over { border: dotted 3px red; } /* Default class applied to    drop zones on over */
 .another-file-over-class { border: dotted 3px green; }

 html, body { height: 100%; }
 </style>

 <div class="container">

 <div class="navbar navbar-default">
    <div class="navbar-header">
        <a class="navbar-brand" href>The screen to upload files</a>
    </div>
 </div>

 <div class="row">

    <div class="col-md-3">

        <h3>Select files</h3>

        <div ng2FileDrop
             [ngClass]="{'nv-file-over': hasBaseDropZoneOver}"
             (fileOver)="fileOverBase($event)"
             [uploader]="uploader"
             class="well my-drop-zone">
            Base drop zone
        </div>

        <div ng2FileDrop
             [ngClass]="{'another-file-over-class': hasAnotherDropZoneOver}"
             (fileOver)="fileOverAnother($event)"
             [uploader]="uploader"
             class="well my-drop-zone">
            Another drop zone
        </div>

        Multiple Selection
        <input type="file" ng2FileSelect [uploader]="uploader" multiple  /><br/>

        Single
        <input type="file" ng2FileSelect [uploader]="uploader" />
    </div>

    <div class="col-md-9" style="margin-bottom: 40px">

        <h3>Files to upload</h3>
        <p>Total: {{ uploader?.queue?.length }}</p>

        <table class="table">
            <thead>
            <tr>
                <th width="50%">Name</th>
                <th>Size</th>
                <th>Progress</th>
                <th>Status</th>
                <th>Actions</th>
            </tr>
            </thead>
            <tbody>
            <tr *ngFor="let item of uploader.queue">
                <td><strong>{{ item?.file?.name }}</strong></td>
                <td *ngIf="uploader.isHTML5" nowrap>{{ item?.file?.size/1024/1024 | number:'.2' }} MB</td>
                <td *ngIf="uploader.isHTML5">
                    <div class="progress" style="margin-bottom: 0;">
                        <div class="progress-bar" role="progressbar" [ngStyle]="{ 'width': item.progress + '%' }"></div>
                    </div>
                </td>
                <td class="text-center">
                    <span *ngIf="item.isSuccess"><i class="glyphicon glyphicon-ok"></i></span>
                    <span *ngIf="item.isCancel"><i class="glyphicon glyphicon-ban-circle"></i></span>
                    <span *ngIf="item.isError"><i class="glyphicon glyphicon-remove"></i></span>
                </td>
                <td nowrap>
                    <button type="button" class="btn btn-success btn-xs"
                            (click)="item.upload()" [disabled]="item.isReady || item.isUploading || item.isSuccess">
                        <span class="glyphicon glyphicon-upload"></span> Upload
                    </button>
                    <button type="button" class="btn btn-warning btn-xs"
                            (click)="item.cancel()" [disabled]="!item.isUploading">
                        <span class="glyphicon glyphicon-ban-circle"></span> Cancel
                    </button>
                    <button type="button" class="btn btn-danger btn-xs"
                            (click)="item.remove()">
                        <span class="glyphicon glyphicon-trash"></span> Remove
                    </button>
                </td>
            </tr>
            </tbody>
        </table>

        <div>
            <div>
                Queue progress:
                <div class="progress" style="">
                    <div class="progress-bar" role="progressbar" [ngStyle]="{ 'width': uploader.progress + '%' }"></div>
                </div>
            </div>
            <button type="button" class="btn btn-success btn-s"
                    (click)="uploader.uploadAll()" [disabled]="!uploader.getNotUploadedItems().length">
                <span class="glyphicon glyphicon-upload"></span> Upload all
            </button>
            <button type="button" class="btn btn-warning btn-s"
                    (click)="uploader.cancelAll()" [disabled]="!uploader.isUploading">
                <span class="glyphicon glyphicon-ban-circle"></span> Cancel all
            </button>
            <button type="button" class="btn btn-danger btn-s"
                    (click)="uploader.clearQueue()" [disabled]="!uploader.queue.length">
                <span class="glyphicon glyphicon-trash"></span> Remove all
            </button>
        </div>

    </div>

</div>

But unfortunately, when I click on the upload button or Upload All button, (this is the demo use from http://valor-software.com/ng2-file-upload/ ) I can't see the request headers in the request.但不幸的是,当我点击上传按钮或全部上传按钮时,(这是来自http://valor-software.com/ng2-file-upload/的演示使用)我看不到请求中的请求标头.

I'm using ng2-file-upload 1.2.0 version我正在使用ng2-file-upload 1.2.0 版本

Any ideas??有任何想法吗??

I did this and it worked just fine.. was able to extract foofoo in my MVC controller:我这样做了,它工作得很好……能够在我的 MVC 控制器中提取 foofoo:

uploader: FileUploader = new FileUploader({
  url: URL,
  headers: [{ name: 'foofoo', value: 'passengerslivesmatter' }]
});

You can add auth token in ng2-file-upload like this:您可以像这样在 ng2-file-upload 中添加身份验证令牌:

  public uploader: FileUploader = new FileUploader({
    url: urlFileUpload,
    authToken: Your value//auth token.

  });

authToken attribute of ng2-file-upload adds token. ng2-file-upload 的 authToken 属性添加了令牌。

你可以像下面这样传递你的令牌:

this.uploader = new FileUploader({ url: URL , authToken: "Bearer " + authService.getToken()});

Basically if you need Bearer Autentification on Post headers基本上,如果您需要对 Post 标头进行承载认证

const uploader: FileUploader = new FileUploader({
  url: URL,
  headers: [{ name: 'Autenfication', value: 'Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJfaWQiOiI1YTIzNDBkOWE0MDM5YTI2MGM1OWYzNTMiLCJleHAiOjE1MTUyMjc5NDcyMzV9.uVpwN9vrjpoKOzNN_DYOgonB1N46Pl' }]
})

fileItem.withCredentials = false;

This work fine.这工作很好。

If you have already uploader is initialized, and want to add headers dynamically based on the user interactions, this is another way to extend the headers如果您已经初始化了uploader器,并希望根据用户交互动态添加标头,这是扩展标头的另一种方法

this.uploader.setOptions({headers:[
      { name: 'user', value: 'visited-column-37' },
      {name: 'type',  value: 'normal'}] 
    });

headers: [{ name: 'Sec-Fetch-Mode', value: 'cors'}, {name: 'Sec-Fetch-Site', value: 'same-site'}]标头:[{ name: 'Sec-Fetch-Mode', value: 'cors'}, {name: 'Sec-Fetch-Site', value: 'same-site'}]

Add the above line if you are having trouble with backend not able to read the Authorization that you are passing in authToken.如果您遇到后端无法读取您在 authToken 中传递的授权的问题,请添加以上行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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