I can't find answer to my problem and I think it's possible in only Vue.js, but I'm not 100% sure. So problem is that. I want user to select file from his computer, it's always will be json file. It is possible to get that file and work with it with just Vue.js or I need some backend to this.
Asked
Active
Viewed 4,434 times
3
-
1Indeed there is no specific need for vue here. You can make use of HTML5 `` tag with [`type=file`](https://stackoverflow.com/q/23344776/4636715) attribute and [limit input types](https://stackoverflow.com/questions/4328947/limit-file-format-when-using-input-type-file). And no, there is no need for a backend service to upload file in your code. – vahdet Dec 03 '19 at 11:18
-
possible on client-side is: to select the file, restrict it to be the only JSON. Then, you may need backend: a server with an endpoint to where you would upload the file & can access it later for some processing. For backend, you can also use some other services such as firebase, s3, etc... where they would provide an API where you can send your JSON file. – Shivam Singh Dec 03 '19 at 11:23
-
@ShivamSingh - absolutely no need for any backend – Jaromanda X Dec 03 '19 at 12:02
1 Answers
8
There is nothing specific to Vue here, and there is no need for a server.
The way to do it is with the special <input type="file">
, and a FileReader()
.
document.getElementById('import').onclick = () => {
const files = document.getElementById('selectFiles').files;
if (files.length <= 0) {
return false;
}
const fr = new FileReader();
fr.onload = e => {
const result = JSON.parse(e.target.result);
const formatted = JSON.stringify(result, null, 2);
document.getElementById('result').innerHTML = formatted;
}
fr.readAsText(files.item(0));
};
<input type="file" id="selectFiles" value="Import" /><br />
<button id="import">Import The File!</button>
<pre id="result"></pre>
Obviously, this code can easily be implemented in a Vue app.

Shaya Ulman
- 1,299
- 1
- 12
- 24