无法在 fetch() POST 请求中包含文件
Unable to include file in fetch() POST request
出于某种原因,我无法通过 fetch 进行文件传输。我的代码真的很简单:
export function updateProfilePicture(apiKey, userID, picture) {
let data = new FormData();
data.append('picture', picture);
return fetch(`${API_URL}/v1/${ROOT}/update_profile_picture/${userID}`,{
headers: {'Authorization': `Token token=${apiKey}`},
method: 'POST',
data: data
}).then(response => response.json());
}
但是,生成的请求似乎不包含任何文件。我错过了什么吗?在上面的例子中,图片是File
的一个实例
可能有两个原因:
data
Fetch API 中的字段称为 body
。使用这个代替 data
属性.
- (可选)您需要添加另一个 header:
'Content-Type', 'multipart/form-data'
详细了解 Fetch API:
出于某种原因,我无法通过 fetch 进行文件传输。我的代码真的很简单:
export function updateProfilePicture(apiKey, userID, picture) {
let data = new FormData();
data.append('picture', picture);
return fetch(`${API_URL}/v1/${ROOT}/update_profile_picture/${userID}`,{
headers: {'Authorization': `Token token=${apiKey}`},
method: 'POST',
data: data
}).then(response => response.json());
}
但是,生成的请求似乎不包含任何文件。我错过了什么吗?在上面的例子中,图片是File
的一个实例可能有两个原因:
data
Fetch API 中的字段称为body
。使用这个代替data
属性.- (可选)您需要添加另一个 header:
'Content-Type', 'multipart/form-data'
详细了解 Fetch API: