尝试上传传递名称的 txt 文件时出现反应错误
React error trying to upload a txt file passing the name
我有一个加载 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
});
这种方法有效,但根据 this formData.append(name, value, filename);
是允许的,但如果我这样做:
formData.append('file', fileContents, 'myFile');
浏览器的控制台大喊:
Uncaught TypeError: Failed to execute 'append' on 'FormData': parameter 2 is not of type 'Blob'
我怎样才能克服这个问题?我在这里错过了什么?
我做了更多 Google 并且我 post 这个解决方案希望任何人都可以使用它:
由于 fileContents
是一个字符串,我需要将其转换为文件,因此我这样做了:
const myBlob = new Blob([fileContents], { type: 'text/plain' });
const myFile = new File([myBlob], { type: 'text/plain' });
然后
formData.append('file', myFile, 'myFile');
很有魅力。所以,如果有更好的方法,请告诉我。
我有一个加载 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
});
这种方法有效,但根据 this formData.append(name, value, filename);
是允许的,但如果我这样做:
formData.append('file', fileContents, 'myFile');
浏览器的控制台大喊:
Uncaught TypeError: Failed to execute 'append' on 'FormData': parameter 2 is not of type 'Blob'
我怎样才能克服这个问题?我在这里错过了什么?
我做了更多 Google 并且我 post 这个解决方案希望任何人都可以使用它:
由于 fileContents
是一个字符串,我需要将其转换为文件,因此我这样做了:
const myBlob = new Blob([fileContents], { type: 'text/plain' });
const myFile = new File([myBlob], { type: 'text/plain' });
然后
formData.append('file', myFile, 'myFile');
很有魅力。所以,如果有更好的方法,请告诉我。