i have an URL which on click download me a file in my computer local but what i want is to store that file in local-storage of my browser not in my computer local in my React app
CodePudding user response:
try using localStorage.setItem(key : value) to store value and to get value localStorage.getItem(key)
Ex: localStorage.setItem("urlcontent", value) localStorage.getItem("urlContent")
for key give a name and for value store downloaded URL content, it is not best practice to store data inside the browser, the browser has 5MB capacity of storage. check this: https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage
CodePudding user response:
Basically, to download a file we create a new a tag and set the url and href to download it as below:
const link = document.createElement("a");
link.href = URL.createObjectURL(new Blob([action.payload.canvasJSON], { type: "application/json" }));
link.download = Math.random().toFixed(3) ".json";
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
If you want to save the content of the file you download in localStorage or Cookies, you just set the content or any information you need like below:
const link = document.createElement("a");
link.href = URL.createObjectURL(new Blob([action.payload.canvasJSON], { type: "application/json" }));
localStorage.setItem(filename, link.href);
link.download = Math.random().toFixed(3) ".json";
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
Of course, you can use other browser storage like cookies and indexDB to achieve the same goal, but beware of that third-party cookies will not be supported in the following year 2023.
Refer to: https://www.cookiebot.com/en/google-third-party-cookies/