Kinh Nghiệm Hướng dẫn Upload file JSON JavaScript 2022

Pro đang tìm kiếm từ khóa Upload file JSON JavaScript được Update vào lúc : 2022-11-12 10:52:00 . Với phương châm chia sẻ Bí kíp Hướng dẫn trong nội dung bài viết một cách Chi Tiết 2022. Nếu sau khi Read Post vẫn ko hiểu thì hoàn toàn có thể lại Comments ở cuối bài để Mình lý giải và hướng dẫn lại nha.

This morning, a student of mine asked me how to use JavaScript to import a JSON file and do something with the data in it. I thought Id write an article about it, because its a really cool browser feature!

Lets dig in.

An example

For this article, were going to look a form element with the #upload ID.

It contains a single field, #file, with a type of file. Fields with this type allow you specify an accept parameter, with a comma-separated list of accepted file types. For our purposes, were going to restrict our uploads to only .json files.

File to upload
Upload

Ill be using a simple wizard.json file for testing.

“name”: “Merlin”,
“age”: “old AF”,
“spells”: [“Dancing brooms”, “Transform into animal”]

You can tải về the source code for todays lesson on GitHub.

Listening for uploads

To get started, were going to use some DOM manipulation fundamentals to detect when the user submits a file.

First, well use the document.querySelector() method to get the #upload and #file elements, and save them to the form and file variables, respectively.

// Get the form and file field
let form = document.querySelector(‘#upload’);
let file = document.querySelector(‘#file’);

Then, well use the Element.addEventListener() method to listen for submit events on the form element. Well use a handleSubmit() function as the callback function.

// Listen for submit events
form.addEventListener(‘submit’, handleSubmit);

Inside the handleSubmit() function, the first thing well do is use sự kiện.preventDefault() to stop the form from reloading the page.

/**
* Handle submit events
* @param Event sự kiện The sự kiện object
*/
function handleSubmit (sự kiện)
// Stop the form from reloading the page
sự kiện.preventDefault();

Next, well check that the file field has an actual file to process using the file.value property, then checking its length property.

If theres no file, well use the return operator to end the callback function.

/**
* Handle submit events
* @param Event sự kiện The sự kiện object
*/
function handleSubmit (sự kiện)
// Stop the form from reloading the page
sự kiện.preventDefault();
// If there’s no file, do nothing
if (!file.value.length) return;

Now, were ready to actually upload the file.

Uploading and processing the JSON file with JavaScript

The FileReader API is an asynchronous set of methods that let you process and read the content of files.

The first thing were going to do is use the new FileReader() constructor to create a new FileReader instance, and assign it to the reader variable.

/**
* Handle submit events
* @param Event sự kiện The sự kiện object
*/
function handleSubmit (sự kiện)
// Stop the form from reloading the page
sự kiện.preventDefault();
// If there’s no file, do nothing
if (!file.value.length) return;
// Create a new FileReader() object
let reader = new FileReader();

To actually read the file, we can use the FileReader.readAsText() method.

We call it on our reader, and pass in the file to read as an argument. We can access the file using the files property on our file field. This returns an array (since [type=”file”]) inputs can tư vấn multiple files.

Well use bracket notation to grab the first (and in our case, only) file.

/**
* Handle submit events
* @param Event sự kiện The sự kiện object
*/
function handleSubmit (sự kiện)
// Stop the form from reloading the page
sự kiện.preventDefault();
// If there’s no file, do nothing
if (!file.value.length) return;
// Create a new FileReader() object
let reader = new FileReader();
// Read the file
reader.readAsText(file.files[0]);

This API is asynchronous, so we need to attach an onload sự kiện handler to the reader object. This will run whenever the reader reads a file.

This needs to be declared before we actually read the file.

To keep our code a bit more organized, well use a named function: logFile(). We dont want it to run immediately, so we leave the parentheses (()) off of it when assigning it to the sự kiện.

/**
* Handle submit events
* @param Event sự kiện The sự kiện object
*/
function handleSubmit (sự kiện)
// Stop the form from reloading the page
sự kiện.preventDefault();
// If there’s no file, do nothing
if (!file.value.length) return;
// Create a new FileReader() object
let reader = new FileReader();
// Setup the callback sự kiện to run when the file is read
reader.onload = logFile;
// Read the file
reader.readAsText(file.files[0]);

The logFile() function receives an implicit sự kiện argument from the FileReader object, so well add it as a parameter.

The sự kiện.target.result property will be a stringified version of the uploaded JSON file. We can pass it into the JSON.parse() method to get a JSON object form it.

For our purposes, well log both the string and parsed JSON. You might want to use properties from the JSON file in your app, save it localStorage, or do something else with it (like send it along to an API).

/**
* Log the uploaded file to the console
* @param sự kiện Event The file loaded sự kiện
*/
function logFile (sự kiện)
let str = sự kiện.target.result;
let json = JSON.parse(str);
console.log(‘string’, str);
console.log(‘json’, json);

Now, whenever a user submits a JSON file, our code will read it and log it to the console.

4069

Clip Upload file JSON JavaScript ?

Bạn vừa đọc tài liệu Với Một số hướng dẫn một cách rõ ràng hơn về Clip Upload file JSON JavaScript tiên tiến và phát triển nhất

Chia Sẻ Link Download Upload file JSON JavaScript miễn phí

Heros đang tìm một số trong những Chia SẻLink Tải Upload file JSON JavaScript Free.

Giải đáp vướng mắc về Upload file JSON JavaScript

Nếu sau khi đọc nội dung bài viết Upload file JSON JavaScript vẫn chưa hiểu thì hoàn toàn có thể lại Comments ở cuối bài để Ad lý giải và hướng dẫn lại nha
#Upload #file #JSON #JavaScript