The Wayback Machine - https://web.archive.org/web/20240707004220/https://www.geeksforgeeks.org/how-to-create-input-field-that-accept-csv-file-in-html/
Open In App

How to create input field that accept CSV file in HTML ?

Last Updated : 24 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

CSV (Comma Separated Values) is a commonly used file format for storing tabular data. To allow users to upload CSV files to a web application, we can create an input field that accepts CSV files in HTML. There are different approaches to achieve this, ranging from the simple “accept” attribute in the input tag to more advanced third-party libraries.

To create an input field that accepts CSV files in HTML, we can use the “input” tag with a type=”file” attribute to create a file upload input field. We can add the accept=”.csv” attribute to limit file types to CSV only. We can also add a name attribute to the input tag to provide a name for the file upload field. When a file is uploaded, it can be accessed using JavaScript and parsed as CSV data. This input field can be used to allow users to upload CSV files to a web application.

Syntax:

<input type="file" accept=".csv">

There are several approaches to creating an input field that accepts CSV files in HTML:

Using the “accept” attribute:  The simplest way is to use the “accept” attribute in the input tag to limit the file type to CSV. 

Using the input element with the “accept” attribute: 

  • Create a standard HTML form with an input element for file upload.
  • Add the “accept” attribute to the input element and set it to “text/csv”.
  • This attribute restricts the file selection to only CSV files.
  • Add the “name” attribute to the input element to identify it on the server side.
  • Finally, specify the “method” and “action” attributes of the form to handle the file upload.

Example: This example shows the use of the above-explained approach.

HTML




<html>
<head>
    <title>
          input field that accept CSV file in HTML 
      </title>
</head>
  
<body>
    <input type="file" name="csvFile" accept=".csv">
</body>
</html>


Output:

csv file using accept method

Explanation: In this example, we create a standard HTML form with an input field for file upload. We add the “accept” attribute to the input tag and set it to “.csv” to restrict file selection to CSV files. We also add the “name” attribute to the input tag to identify the file on the server side. Finally, we specify the “method” and “action” attributes of the form to handle the file upload.

Using the drag-and-drop: To allow users to select CSV files using drag-and-drop in HTML, you can use the HTML5 drag-and-drop API along with JavaScript to handle the drag-and-drop events and file selection.

Using the drag-and-drop feature: 

  • Create an HTML button to act as the dropzone for the CSV file.
  • Use the Drag and Drop API to allow users to drag and drop CSV files onto the button.
  • Add event listeners to the button to listen for “dragover”, “dragleave”, and “drop” events.
  • On the “drop” event, check if the dropped file is a CSV file and handle it accordingly.
  • If the file is a CSV file, call a function to handle the file, otherwise, show an error message.

Example: This example shows the use of the above-explained approach.

HTML




<!DOCTYPE html>
<html>
<head>
    <title>csv file select</title>
</head>
  
<body>
    <button id="csv-dropzone" type="file">
          Drop CSV file here
      </button>
  
    <script>
        const csvDropzone = document.getElementById("csv-dropzone");
  
        csvDropzone.addEventListener("dragover", function (event) {
            event.preventDefault();
            csvDropzone.classList.add("dragover");
        });
  
        csvDropzone.addEventListener("dragleave", function (event) {
            event.preventDefault();
            csvDropzone.classList.remove("dragover");
        });
  
        csvDropzone.addEventListener("drop", function (event) {
            event.preventDefault();
            csvDropzone.classList.remove("dragover");
            const csvFile = event.dataTransfer.files[0];
  
            if (csvFile.type === "text/csv" || 
                csvFile.type === "application/vnd.ms-excel") {
                alert("csv file has been selected");
                handleCsvFile(csvFile);
            } else {
                alert("Please drop a CSV file.");
            }
        });
    </script>
</body>
</html>


Output:

select csv file using drop down mathod

Explanation: In this example, a button can be used to select a CSV file. The JavaScript code adds event listeners to the button for “dragover”, “dragleave”, and “drop” events. The “dragover” and “dragleave” events add and remove a CSS class to indicate that a file is being dragged over the button. The “drop” event retrieves the CSV file from the drag event and checks its type. If the file is a CSV file, an alert is displayed and the file is handled. If the file is not a CSV file, an alert is displayed asking the user to drop a CSV file.

Using a third-party library: There are several third-party libraries available that provide a more advanced CSV file upload functionality. But I will use the Dropzone.js library to enable users to upload CSV files using drag-and-drop in HTML. 

The code creates a form with a dropzone element that users can drag and drop CSV files onto. The Dropzone.js library is initialized with options that limit the file selection to CSV files only and allow for only one file to be uploaded at a time.

Using a third-party library:

  • Create an HTML page with a div element to receive the CSV file using the Dropzone.js library.
  • Use the Drag and Drop API provided by Dropzone.js to allow users to drag and drop CSV files onto the dropzone.
  • Add an event listener to the dropzone to listen for the “drop” event.
  • Use the Dropzone.js library to parse the CSV file in JavaScript.
  • Use AJAX to send the CSV file to the server-side script.
  • The server-side script can handle the file and perform any necessary actions with it.

Example: This example shows the use of the above-explained approach..

HTML




<!DOCTYPE html>
<html>
<head>
    <title>csv file</title>
    <link rel="stylesheet" href=
    <script src=
      </script>
</head>
  
<body>
    <form id="csv-upload-form">
        <div class="dropzone" id="csv-dropzone">
            <div class="dz-message">
                Drop CSV file here
            </div>
        </div>
    </form>
  
    <script>
        const csvDropzone = new Dropzone("#csv-dropzone", {
            url: "/upload",
            acceptedFiles: ".csv",
            maxFiles: 1,
            init: function () {
                this.on("success", function (file, response) {
                    console.log(response);
                });
            }
        });
    </script>
</body>
</html>


Output:

select csv file  using third party library 

Explanation: This code creates a form with a Dropzone area that allows the user to drag and drop a CSV file onto it. The accepted file type is limited to CSV files using the acceptedFiles option in the Dropzone() constructor. When a file is successfully uploaded, the success event is triggered, and the console.log() function outputs the server response. This implementation uses the Dropzone.js library to handle the drag-and-drop file selection and uploading.



Similar Reads

Which input type is used to hide the input field to be displayed in HTML Form ?
The form tag is generally used to create forms for entering data. We can use different form tag attributes like text boxes, text area, checkboxes, radio buttons, buttons, dropdown list, etc. to collect data from the users. We need to use the HTML &lt;input type=”hidden”&gt; type for hiding the input field. Using this attribute, the input field will
1 min read
HTML | DOM Input FileUpload accept Property
The DOM Input FileUpload accept Property in HTML DOM is used to set or return the value of the accept attribute of the file upload button. The accept attribute specifies the types of files which are acceptable by that the server. Syntax: Return the accept property:fileuploadObject.acceptSet the accept property:fileuploadObject.accept="audio/*, vide
2 min read
HTML &lt;input&gt; accept Attribute
The HTML &lt;input&gt; accept Attribute is used to specify the file types that the input field can accept, restricting the file selection to those specified types, such as image/* for images or .pdf for PDF files. HTML &lt;input&gt; accept Attribute Syntax:  &lt;input accept = "file_extension | audio/* | video/* | image/* | media_type"&gt;HTML &lt;
3 min read
How to create a hidden input field in form using HTML ?
In this article, we will learn how to add a hidden input field into our form using HTML. A hidden control stores the data that is not visible to the user. It is used to send some information to the server which is not edited by the user. Normally, this hidden field usually contains the value which is common for all the users. The value must be reco
2 min read
Create OTP Input Field using HTML CSS and JavaScript
In this article, we will explore how to build an OTP (One-Time Password) input box, which is commonly used on many websites. This interactive and engaging UI element allows users to enter their OTP conveniently and efficiently. We will walk through the step-by-step process of creating this functionality using HTML, CSS, and JavaScript. Setting up t
3 min read
How to validate if input date (end date) in input field must be after a given date (start date) using express-validator ?
In HTML forms, we often required validation of different types. Validate existing email, validate password length, validate confirm password, validate to allow only integer inputs, these are some examples of validation. In certain cases, we want the user to type a date that must come after some given date(Ex. 'end date' must be after 'start date')
5 min read
How to validate if input in input field exactly equals to some other value using express-validator ?
In HTML forms, we often required validation of different types. Validate existing email, validate password length, validate confirm password, validate to allow only integer inputs, these are some examples of validation. In certain cases, we want the user to type some exact value and based on that we give the user access to the request or deny the r
4 min read
How to validate if input in input field has alphanumeric characters only using express-validator ?
In HTML forms, we often required validation of different types. Validate existing email, validate password length, validate confirm password, validate to allow only integer inputs, these are some examples of validation. In a certain input field, only alphanumeric characters are allowed i.e. there not allowed any special characters. We can also vali
4 min read
How to validate if input in input field has base64 encoded string using express-validator ?
In HTML forms, we often required validation of different types. Validate existing email, validate password length, validate confirm password, validate to allow only integer inputs, these are some examples of validation. If In a certain input field only base 64 encoded string are allowed i.e there not allowed any other form of string which not const
4 min read
How to validate if input in input field has boolean value using express-validator ?
In HTML forms, we often required validation of different types. Validate existing email, validate password length, validate confirm password, validate to allow only integer inputs, these are some examples of validation. In a certain input field, only boolean value i.e. true or false are allowed. We can also validate these input fields to accept onl
4 min read
three90RightbarBannerImg