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

Angular文件上传报错:数字值非法字符及不可重复请求实体问题

问题分析与解决方法

错误根源

  1. JSON解析错误:后端Jersey框架尝试将multipart/form-data格式的请求体当作JSON解析,触发语法错误。原因是Angular的$http服务默认会把Content-Type设为application/json,后端收到后按JSON规则解析FormData内容,自然出现字符格式不匹配的错误。
  2. 不可重复请求实体错误:当请求因Content-Type错误触发重试时,FormData作为不可重复读取的实体,就会抛出NonRepeatableRequestException。

Postman能正常运行是因为它会自动为FormData请求设置正确的multipart/form-data头,并生成对应的边界标识(boundary),无需手动配置。

修复步骤

修改Angular代码中的$http配置,确保正确发送FormData:

  • 配置transformRequest: angular.identity,阻止$http自动序列化请求体
  • 显式设置Content-Type为undefined,让浏览器自动添加正确的multipart/form-data头及边界

修改后的代码

importCatalogEntityApi = (
    file: File
): IDeferred<IComponentsPagination> => {
        
    const defer = this.$q.defer<IComponentsPagination>();
    
    let formData: FormData = new FormData();
    formData.append("details", "{}");
    formData.append('payload', file, file.name);

    const options = {
        transformRequest: angular.identity,
        headers: { 'Content-Type': undefined }
    };

    this.$http
    .post("http://.../upload", formData, options)
    .then(
        (response: any) => {
            console.log("success: " + response)
            const defferObj = this.convertEntitiesResponse(response);
            defer.resolve(defferObj);
        },
        (response) => {
            console.log("failure: " + response)
            defer.reject(response);
        }
    );
    
    return defer;
};

关键说明

  • transformRequest: angular.identity:告诉Angular不要对FormData做任何序列化处理,直接传递原始数据。
  • headers: { 'Content-Type': undefined }:让浏览器自动根据FormData生成带边界标识的multipart/form-data头,这是后端正确解析表单数据的核心。如果手动设置multipart/form-data但不指定boundary,后端依然无法正确解析请求体。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 23:46:00