Angular: 使用 Angular HTTP 表单数据发送远程文件
Angular: Send remote file with Angular HTTP form-data
我的服务器端点上有一个文件可用 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 的远程文件吗?还是需要先下载文件再发送?我该怎么做?
您不能只 link 发送到一个文件。 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);
});
});
我的服务器端点上有一个文件可用 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 的远程文件吗?还是需要先下载文件再发送?我该怎么做?
您不能只 link 发送到一个文件。 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);
});
});