我有一个加载txt文件的组件然后我试图上传那个txt文件在请求中传递文件名,我得到的文件是这样的
const fetch = ({ target }) => {
const reader = new FileReader();
const file = target.files[0];
if (file) {
reader.readAsText(file);
reader.onloadend = e => {
setFileContents(e.target.result);
};
}
};
,我试着像这样上传它:
const URL = 'myURL';
const formData = new FormData();
formData.append('file', fileContents);
fetch(URL, {
method: 'PATCH',
headers: // ... my headers,
body: formData
})
.then(response => response.json())
.then(data => {
// success
})
.catch(() => {
// error
});
这种方法是有效的,但是,根据这个formData.append(name, value, filename);
是允许的,但是如果我这样做:
formData.append('file', fileContents, 'myFile');
浏览器的控制台大喊:
Uncaught TypeError: Failed to execute 'append' on 'FormData:参数2不是'Blob'类型
我怎样才能克服这个?我遗漏了什么?
我做了更多的谷歌,我发布了这个解决方案,希望任何人都可以使用它:
因为fileContents
是一个字符串,我需要把它变成一个文件,我这样做:
const myBlob = new Blob([fileContents], { type: 'text/plain' });
const myFile = new File([myBlob], { type: 'text/plain' });
然后
formData.append('file', myFile, 'myFile');
很有魅力。所以,如果有更好的方法,请告诉我。