You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular13升级至14后ng2-file-upload@3.0.0 Content-Length报错求助

解决方案:ng2-file-upload 3.0.0 Content-Length 类型错误

错误原因分析

这个错误是因为 ng2-file-upload 3.0.0 版本对请求头的类型校验更严格了。当你初始化时传入 url: undefined,库内部构造上传请求时,会错误地将文件大小(数值类型,比如你的138)直接作为 Content-Length 的值传入,而 XMLHttpRequest 要求该头的值必须是字符串或数组类型,从而触发类型错误。

另外,新版本强制要求传入 URL,并不代表可以用 undefined 占位——库的内部逻辑会认为这是一个无效的上传目标,进而导致请求头处理逻辑异常。

修复步骤

1. 给指令添加动态 URL 输入属性

不要在构造函数中硬编码 url: undefined,而是通过 @Input() 让使用该指令的组件传入有效上传地址,确保上传时有合法的请求目标:

import { Directive, Input, OnInit } from '@angular/core';
import { FileUploader, FileItem } from 'ng2-file-upload';

@Directive({
  selector: '[appFileUploader]'
})
export class AppFileUploaderDirective extends FileUploader implements OnInit {
  // 新增输入属性接收上传URL
  @Input() uploadUrl!: string;

  constructor(private allowedExtensions?: string) {
    // 初始化时用空字符串占位,后续动态替换
    super({ url: '' });
    this.setOptions({
      autoUpload: true,
      removeAfterUpload: true,
      filters: this.allowedExtensions
        ? this.getExtensionFilter(this.allowedExtensions)
        : [],
    });
  }

  ngOnInit(): void {
    // 在初始化阶段设置实际的上传URL
    if (this.uploadUrl) {
      this.setOptions({ url: this.uploadUrl });
    }
  }

  private getExtensionFilter(extensions: string) {
    return [{
      name: 'extensionFilter',
      fn: (item: FileItem) => {
        const allowedExts = extensions.split(',').map(ext => ext.toLowerCase());
        const fileExt = item.file.name.split('.').pop()?.toLowerCase();
        return fileExt ? allowedExts.includes(fileExt) : false;
      }
    }];
  }
}

2. 在组件中传入有效 URL

使用该指令时,通过属性绑定传入实际的上传接口地址:

<input type="file" appFileUploader [uploadUrl]="'/api/files/upload'" />

3. 检查自定义请求头(如果有)

如果你手动设置过 Content-Length 头,确保将数值转为字符串类型:

// 错误写法
this.setOptions({
  headers: [{ name: 'Content-Length', value: 138 }]
});

// 正确写法
this.setOptions({
  headers: [{ name: 'Content-Length', value: '138' }]
});

内容的提问来源于stack exchange,提问作者Danilo Bassi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 19:47:23