How to add Custom Headers in ng2-file-upload

时间:2017-03-02 23:41:59

标签: angular file-upload

I'm experimenting with ng2-file-upload, the problem is I can't set the custom headers. So far I've done this

In the upload-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

    <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.

I'm using ng2-file-upload 1.2.0 version

Any ideas??

6 个答案:

答案 0 :(得分:9)

我这样做了它工作得很好..能够在我的MVC控制器中提取foofoo:

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

答案 1 :(得分:7)

您可以在ng2-file-upload中添加身份验证令牌,如下所示:

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

  });

ng2-file-upload的authToken属性添加了令牌。

答案 2 :(得分:1)

您可以像下面一样传递您的令牌:

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

答案 3 :(得分:0)

如果您已经初始化uploader,并且想根据用户交互动态添加标头,则这是扩展标头的另一种方法

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

答案 4 :(得分:0)

标题:[{名称:“ Sec-Fetch-Mode”,值:'cors'},{名称:'Sec-Fetch-Site',值:'same-site'}]

如果您在后端无法读取正在传递的authToken的授权中遇到麻烦,请添加以上行。

答案 5 :(得分:-1)

基本上,如果您需要在帖子标题上使用承载Autentification

/*
@(#)File:           $RCSfile: isqrt.c,v $
@(#)Version:        $Revision: 1.14 $
@(#)Last changed:   $Date: 2017/12/23 17:12:52 $
@(#)Purpose:        Integer square root calculation
@(#)Author:         J Leffler
@(#)Copyright:      (C) JLSS 1991-2017
*/

/*TABSTOP=4*/

#ifndef lint
/* Prevent over-aggressive optimizers from eliminating ID string */
extern const char jlss_id_isqrt_c[];
const char jlss_id_isqrt_c[] = "@(#)$Id: isqrt.c,v 1.14 2017/12/23 17:12:52 jleffler Exp $";
#endif /* lint */

/* Configuration: use public domain implementation unless -DUSE_JLSS_ISQRT */
#undef USE_PUBLIC_DOMAIN
#ifndef USE_JLSS_ISQRT
#define USE_PUBLIC_DOMAIN
#endif /* USE_JLSS_ISQRT */

#include "isqrt.h"

#if defined(USE_TIMING_TESTS)
extern int32_t isqrt_jl(uint32_t x);
extern int32_t isqrt_ct(uint32_t x);
#else
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-macros"
#define isqrt_jl(x) isqrt_32(x)
#define isqrt_ct(x) isqrt_32(x)
#pragma GCC diagnostic pop
#endif /* USE_TIMING_TESTS */

#if !defined(USE_PUBLIC_DOMAIN) || defined(USE_TIMING_TESTS)
/*
** Algorithm by J Leffler: slow but correct
*/
int32_t isqrt_jl(uint32_t x)
{
    uint32_t x1;
    uint32_t x2;

    /* Special cases:              */
    /* x == 0 => return 0 CORRECT */
    /* x <  4 => return 1 CORRECT */
    if (x < 4)
        return(x > 0);

    x1 = x / 4;
    while ((x2 = ((x / x1 + x1) / 2)) != x1)
    {
        if (x2 == x1 + 1 && x2 > x / x2 && x1 < x / x1)
            return(x1);
        x1 = x2;
    }
    return(x1);
}
#endif /* !USE_PUBLIC_DOMAIN || USE_TIMING_TESTS */

#if defined(USE_PUBLIC_DOMAIN) || defined(USE_TIMING_TESTS)
/*
** Code by Chris Torek: fast and correct
*/
/*
** From: edelsohn@sccs.syr.edu (David Edelsohn)
** Subject: Re: quick sqrt()
** Message-ID: <1991Aug14.161849.18548@rodan.acs.syr.edu>
** Date: 14 Aug 91 20:18:49 GMT
** Organization: Syracuse Center for Computational Science/Dept of Physics
**
** I tried replying to the poster but my email bounced and Chris Torek
** has not jumped in with his previous solution, so I will repost it for him:
** >From: chris@mimsy.umd.edu (Chris Torek)
** >Subject: Re: Integer Square Root (Was Re: # to the nth power)
**
** Integer square root routine, good for up to 32-bit values.
** Note that the largest square root (that of 0xffffffff)is
** 0xffff, so the result fits in a regular unsigned and need
** not be `long'.
**
** Original code from Tomas Rokicki (using a well known algorithm).
** This version by Chris Torek, University of Maryland.
**
** This code is in the public domain.
*/
int32_t isqrt_ct(uint32_t v)
{
    uint32_t t = 1L << 30;
    uint32_t r = 0;
    uint32_t s;

#undef STEP
#define STEP(k) \
    s = t + r; \
    r >>= 1; \
    if (s <= v) { \
        v -= s; \
        r |= t; \
    }

    STEP(15);
    t >>= 2;
    STEP(14);
    t >>= 2;
    STEP(13);
    t >>= 2;
    STEP(12);
    t >>= 2;
    STEP(11);
    t >>= 2;
    STEP(10);
    t >>= 2;
    STEP(9);
    t >>= 2;
    STEP(8);
    t >>= 2;
    STEP(7);
    t >>= 2;
    STEP(6);
    t >>= 2;
    STEP(5);
    t >>= 2;
    STEP(4);
    t >>= 2;
    STEP(3);
    t >>= 2;
    STEP(2);
    t >>= 2;
    STEP(1);
    t >>= 2;
    STEP(0);
    return (int32_t)r;
}
#endif /* USE_PUBLIC_DOMAIN || USE_TIMING_TESTS */

#if defined(TEST)
#include <stdio.h>
#include <math.h>
#include <inttypes.h>

#if defined(USE_TIMING_TESTS)
/*
** Representative timings - (2011-11-27 on MacOS X 10.7.2 on a 2.3 GHz Intel Core i7
** with 8 GB 1333 MHz DDR3 memory).
**
** CT 0.482771 (1370731968); JL 2.074758 (1370731968); MT 0.125003 (1507082656)
** CT 0.404681 (1370731968); JL 1.825984 (1370731968); MT 0.086421 (1507082656)
** CT 0.509388 (1370731968); JL 1.900582 (1370731968); MT 0.094746 (1507082656)
** CT 0.534594 (1370731968); JL 1.866929 (1370731968); MT 0.095474 (1507082656)
** CT 0.447996 (1370731968); JL 2.211031 (1370731968); MT 0.120391 (1507082656)
**
** With the augmented test timing the conversion to double, use library
** square root, and convert back to integer too, the results (2017-12-23
** on macOS 10.13.2 on a 2.7 GHz Intel Core i7 with 16 GiB 2133 Mhz
** LPDDR3 memory) were:
**
** CT 0.217224 (1370731968); JL 1.479817 (1370731968); DB 0.125086 (1370731968); MT 0.086683 (1507082656)
** CT 0.211790 (1370731968); JL 1.478602 (1370731968); DB 0.129983 (1370731968); MT 0.085262 (1507082656)
** CT 0.213528 (1370731968); JL 1.478100 (1370731968); DB 0.124773 (1370731968); MT 0.082611 (1507082656)
** CT 0.212352 (1370731968); JL 1.494118 (1370731968); DB 0.130582 (1370731968); MT 0.085290 (1507082656)
** CT 0.211442 (1370731968); JL 1.499416 (1370731968); DB 0.127462 (1370731968); MT 0.082682 (1507082656)
**
** Note that on a machine with hardware floating point, the system
** library is close to twice as fast as the CT algorithm, which is about
** 7 times as fast as the JL algorithm.  If the CPU doesn't have
** hardware floating point, then the integer algorithms will be far
** faster than simulated floating point.  This does demonstrate the
** importance of benchmarking, though.
*/

#include "timer.h"

enum { ITERATIONS = 100000 };

static inline uint32_t next_x(uint32_t x)
{
    return (234ULL * x) / 213ULL + 1;
}

extern int32_t isqrt_mt(uint32_t x);
extern int32_t isqrt_db(uint32_t x);

/* Empty isqrt function - measure function call/return overhead */
int32_t isqrt_mt(uint32_t x)
{
    return x;
}

/* Double isqrt function - convert to double, use standard sqrt function, convert back */
int32_t isqrt_db(uint32_t x)
{
    /* Shorthand for: double d = x; d = sqrt(d); x = d; return x; */
    return sqrt(x);
}

typedef int32_t (*Sqrt_Fn)(uint32_t x);

typedef struct Time_Test
{
    Sqrt_Fn     fn;
    const char *prefix;
    const char *tag;
} Time_Test;

static const Time_Test tests[] =
{
    {   isqrt_ct,   "", "CT" },     /* Public domain (Chris Torek) algorithm */
    {   isqrt_jl, "; ", "JL" },     /* JLSS algorithm */
    {   isqrt_db, "; ", "DB" },     /* Double algorithm */
    {   isqrt_mt, "; ", "MT" },     /* Empty algorithm */
};
enum { NUM_TESTS = sizeof(tests) / sizeof(tests[0]) };

static void time_isqrt_function(Sqrt_Fn fn, Clock *clk, uint32_t *acc)
{
    clk_start(clk);
    for (uint32_t i = 0; i < ITERATIONS; i++)
    {
        for (uint32_t x = 0; x < UINT32_MAX / 2; x = next_x(x))
        {
            int32_t v = (*fn)(x);
            *acc += v + i;
        }
    }
    clk_stop(clk);
}

static void time_test(const Time_Test *test)
{
    Clock clk;
    uint32_t acc = 0;
    char buffer[32];
    time_isqrt_function(test->fn, &clk, &acc);
    printf("%s%s %8s (%" PRIu32 ")", test->prefix, test->tag,
           clk_elapsed_us(&clk, buffer, sizeof(buffer)), acc);
}

int main(void)
{
    for (int i = 0; i < NUM_TESTS; i++)
        time_test(&tests[i]);
    putchar('\n');
    return 0;
}

#elif defined(USE_PUBLIC_DOMAIN)
int main(void)
{
    uint32_t l;
    char            buf[100];

    for (;;)
    {
        (void)printf("gimme a number> ");
        if (fgets(buf, sizeof buf, stdin) == NULL)
            break;
        /* should use strtoul here but some do not have it */
        if (sscanf(buf, "0x%" SCNx32, &l) != 1 &&
            sscanf(buf, "0%"  SCNo32, &l) != 1 &&
            sscanf(buf, "%"   SCNu32, &l) != 1 &&
            sscanf(buf, "%"   SCNx32, &l) != 1)
            (void)printf("that was not a number\n");
        else
            (void)printf("root(%" PRIu32 ") => %" PRIu32 " sqrt(%" PRIu32 ") => %.17g\n",
                          l, isqrt_32(l), l, sqrt((double)l));
    }
    putchar('\n');
    return(0);
}

#else

static const uint32_t tests[] = {
    0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 16, 24, 25, 9999, 10000,
    4294705155, 4294705156, 4294705157, 0xFFFFFFFE, 0xFFFFFFFF,
};

#define DIM(x)  (sizeof(x)/sizeof(*(x)))

int main(void)
{
    int             i;

    for (i = 0; i < DIM(tests); i++)
    {
        uint32_t r = isqrt_32(tests[i]);
        assert(r * r <= tests[i]);
        // assert((r+1) * (r+1) > tests[i]);
        // But avoid overflows!
        assert(tests[i] / (r + 1) < (r + 1));
        printf("ISQRT(%" PRIu32 ") = %" PRId32 "\n", tests[i], r);
    }
    return(0);
}

#endif /* USE_PUBLIC_DOMAIN */
#endif /* TEST */

这项工作很好。