在vue3 SPA中,我想将一个对象保存到本地文件系统,然后能够将其上传回来以恢复该对象。
我可以用这种方式将对象保存到文件中。
<ButtonExport
:title="i18n.$t('Save the object to file ')"
@clicked="saveToFile(object)"
bgcolor="red"
/>
function saveToFile(model) {
const data = JSON.stringify(model);
const blob = new Blob([data], {type: 'text/plain' });
const myFile = new File([blob],'test.txt',{type: blob.type});
const link = document.createElement('a');
link.style.display = "none";
link.href = URL.createObjectURL(myFile);
link.download =myFile.name
// It needs to be added to the DOM so it can be clicked
document.body.appendChild(link);
link.click();
URL.revokeObjectURL(link.href);
link.parentNode.removeChild(link);
}
然后为了取回json文本内容,我这样做
<input
type="file"
@change="onFileChanged($event)"
accept=".txt"
/>
const uploaded_file = ref();
function onFileChanged (event) {
const files = event.target.files;
uploaded_file.value = files[0];
let reader = new FileReader();
let text=reader.readAsText(uploaded_file)
console.log(text);
}
But, unfortunately I get an error message when attempting to read the file.
Uncaught TypeError: FileReader.readAsText: Argument 1 does not implement interface Blob.
onFileChanged ...
Could somebody help me fix this error?
const myObject = ref();
const uploaded_file = ref();
function onFileChanged(event) {
myObject.value = null;
const files = event.target.files;
uploaded_file.value = files[0];
let reader = new FileReader();
reader.addEventListener('load', () => {
console.log('load event');
myObject.value = JSON.parse(reader.result);
console.log(myObject);//correct, I get the object back.
}, false);
reader.readAsText(uploaded_file.value);
}