angular - Angular:使用 Angular HTTP 表单数据发送远程文件
问题描述
我的服务器端点上有一个文件可用http://xyz/file
。
我想使用 multipart/form-data 通过 HTTP POST 在 Angular 6 中发送这个文件。感谢这个相关的问题,这是我的方法:
const filePath = 'http://xyz/file'
const formData = new FormData();
formData.append('file', filePath);
this.http.post(endpoint, formData).subscribe(response => {
console.log(response);
});
问题是,如果我指定文件端点的文件路径而不是文件本身,这似乎不起作用。尝试此操作时,我在控制台中收到错误消息ERROR TypeError: "Argument 2 of FormData.append is not an object."
。
我该如何解决这个问题?我可以以某种方式使用远程文件进行 POST 吗?还是我需要先下载文件然后发送?我该怎么做?
解决方案
您不能只发送文件的链接。Formdata 字段期望具有文件内容。您可以分两步执行此操作
- 创建一个函数将远程文件下载到 Blob
- 通过 Post 请求发送 blob
fetch('https://some/file/here.png')
.then(res => res.blob()) // Gets the response and returns it as a blob
.then(blob => {
var formData = new FormData();
formData.append("file", blob);
this.http.post(endpoint, formData).subscribe(response => {
console.log(response);
});
});
推荐阅读
- postgresql - 如何从 Postgres 中的文本中提取 n-gram 单词序列
- sql - SQL Server:在不同的插入语句后更新主键
- sql-server - SQL Server:WHERE 子句中的 ROW_NUMBER() 返回“无效的列名”
- vb.net - 通过 ADOX.Table 创建数据库列
- css - Sass 文件夹输出到 CSS 文件夹
- c# - 如何从组合框将参数传递给 devexpress XtraReport
- go - 更新特定的 bin/column 而不是所有在 Aerospike 的 Table/set 中
- react-native - 单击 WebView 上的链接并在浏览器中打开 url
- python - fill_between 不对相邻间隔着色
- unity3d - Unity:多个实例共享一个 AudioSource