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

Angular 5如何将File/Blob数据流以JSON格式提交?遇FileReader获取流问题

在Angular 5中处理File/Blob并以JSON格式提交的解决方案

嘿,我来帮你捋清楚这个问题~首先明确回答你:完全可以把File或Blob的数据流处理成JSON格式提交,你当前遇到的fr.result为空的问题,是因为没注意到FileReader是异步操作导致的。

你的代码问题分析

你写的fr.readAsText(blobfile)是异步执行的——调用这个方法后,浏览器会在后台读取文件内容,不会阻塞后续代码运行。所以你紧接着就console.log(fr.result)的时候,读取操作还没完成,自然拿不到有效结果。

修正后的FileReader使用方式

你需要通过监听FileReader的onload事件,等读取完成后再获取结果并处理:

let blobfile = new Blob([this.curResume]);
let fr = new FileReader();

// 监听读取完成事件,读取结束后才会触发
fr.onload = () => {
  // 此时fr.result已经是读取到的文本内容
  console.log('读取到的内容:', fr.result);
  
  // 如果内容是JSON格式,解析成JavaScript对象
  try {
    const jsonData = JSON.parse(fr.result as string);
    
    // 用Angular的HttpClient提交JSON数据
    this.http.post('/你的接口地址', jsonData)
      .subscribe({
        next: (response) => console.log('提交成功!', response),
        error: (err) => console.error('提交失败:', err)
      });
  } catch (e) {
    console.error('内容不是合法的JSON格式:', e);
  }
};

// 启动读取操作
fr.readAsText(blobfile);

更简洁的替代方案(无需FileReader)

除了FileReader,你还可以用Response对象来读取Blob内容,写法更简洁直观:

let blobfile = new Blob([this.curResume]);

// 读取Blob为文本,再解析成JSON
new Response(blobfile).text().then(text => {
  const jsonData = JSON.parse(text);
  this.http.post('/你的接口地址', jsonData).subscribe(...);
}).catch(err => {
  console.error('读取Blob失败:', err);
});

额外提醒

如果你的this.curResume本身就是一个JavaScript对象,其实不需要转成Blob再读取——直接作为请求体提交给HttpClient即可,HttpClient会自动帮你处理成JSON格式的请求:

// 如果this.curResume本身是对象,直接提交
this.http.post('/你的接口地址', this.curResume).subscribe(...);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 08:38:34