是否可以用fetch
上传文件?我不是在谈论FormData
,但是我想成为HTTP
PUT
的实际主体,而Content-Type
才是正确的ContentType的文件?
如果无法使用fetch
,是否不能使用XMLHttpRequest
?该代码对我不起作用(事件是drop
事件):
fetch('/foo', {
method: 'PUT',
body: event.dataTransfer.files[0],
});
编辑:
我专门谈论的是FILE上传。如果body
是文本,则此[[does有效,但如果其FILE
/ BLOB
则不起作用!
const body = new FormData();
const file = event.dataTransfer.files[0];
body.append('files', file , file.name);
fetch('/foo', {
method: 'PUT',
body
});
但是,如果您只想直接发送数据,则必须更改标题并使用Blob
:
const body = new Blob(event.dataTransfer.files, { type: 'application/octet-stream' }); fetch('/foo', { method: 'PUT', headers: new Headers({ 'Content-Type': 'application/octet-stream' }), body });