utf-8 Codec Cant Decode Byte 0x89 in Position 323 Invalid Start Byte Angularjs Upload Image
Read Fourth dimension: 6 mins Languages:
This post will show you how to upload CSV files data to AngularJS, read the data, and and then convert information technology to JSON for processing. So, yous'll see how to do the whole thing in contrary and download a CSV information dump from AngularJS.
CSV files are preferred considering of their simplicity. They are too widely supported by many types of programs and provide a straightforward mode to represent spreadsheet data.
Prerequisites
Before you lot get started with this tutorial, make sure you take Node.js installed on your calculator. If you don't have it yet, head over to the official website and install it.
You should too have a basic understanding of the following technologies:
- HTML
- CSS
- JavaScript
If you already have Node.js accept installed, check if you have the latest versions of Node and NPM.
node -5 npm -5
CSV Modules in Athwart
In that location are several ways of manipulating CSV in Athwart, and they include:
- Papa Parse: Papa Parse is a powerful CSV parser which is capable of parsing CSV strings in small and large files as well as converting back to JSON. We will be using this library in this tutorial.
-
csvtojson: This is a node package which is besides unproblematic to use. - File Reader: Information technology is used to read the contents of files using
FileorBlobobjects to specify the file to exist read. However, this is non an efficient way considering you still have to loop through all the lines of the CSV and soJSON.stringifythe results.
Getting Started
Our goal is to exist able to do the following:
- download a CSV file on the client side
- upload a CSV file
- read a CSV file
- catechumen CSV file data to JSON for processing
Our interface should expect something like this:
We will first showtime by writing the HTML code for the interface shown above.
Create a folder named my_project, cd into the project binder, and create two files:home.html and app.js.
mkdir my_project cd my_project touch home.html impact app.js
Since we volition be using the Papa Parse module, caput over to the official site and download the library. Side by side, extract the contents and save thepapaparse.js and papaparse.min.js files in your projection binder. Your projection construction should look similar this:
my_project/ app.js habitation.html papaparse.js papaparse.min.js
Below is the HTML code for creating our interface. Save it every bit home.html .
<!DOCTYPE html ng-app="myApp" ng-strict-di="true"> <html lang="en" ng-app="myApp" class="no-js"> <!--<![endif]--> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/one.7.1/jquery.min.js" type="text/javascript"></script> <script src="papaparse.js"></script> <script src="papaparse.min.js"></script> <body ng-controller = "CsvCtrl"> <section class="content"> <div class="row"> <div class="col-doc-12"> <div class="panel-heading"><potent>BULK Meridian UP</strong> <small></pocket-sized></div> <div class="box box-info"> <div class = "instructions"> <ol> <li>The Excel file should contain 3 columns </li> <li>The beginning column contains the <stiff>Reference</strong></li> <li>The second cavalcade contains the <stiff>Commencement name</stiff></li> <li>The third column contains the <strong>Last name </strong> </li> <li>The second column contains the <strong>Date of Birth</stiff></li> <li>The third column contains the <stiff>Sexual activity</strong>of the person</li> </ol> <div course="box-body table-responsive"> <p>The column headers should exist <strong>Reference</stiff> ,<potent>First_name</strong> ,<strong>Last_name</stiff>,<strong>Dob</strong>,<strong>Sexual practice</strong></p> <p> A sample file is available for download</p> <class> <button data-ng-click="download()">Download CSV</button> </course> </div> </div> <div grade="box-torso table-responsive"> <60 minutes> <hr> <!-- course start --> <p>Your uploaded csv file will be shown to you in a preview for Confirmation</p> <course function="class" class="form-horizontal" name="bulkDirectForm" method="post" enctype="multipart/course-data" novalidate> <div class="box-trunk"> <div id="letters" class="alert alert-success" data-ng-show="letters" data-ng-bind="messages"></div> <div id="warning" form="alert alarm-alert" information-ng-evidence="alert" data-ng-demark="warning"></div> <div class="form-group"> <div grade="col-sm-10"> <input type="file" form="form-command" id="bulkDirectFile" placeholder="CSV file with telephone numbers and amount" ng-model="prd.bulk_direct_file" required take=".csv"> </div> <div grade="col-sm-ii"> <push type="submit" class="btn btn-block btn-info" ng-hide="myVar" data-ng-click="submitForm(bulkDirectForm)">Upload!</button> </div> <br> <br> <div grade="col-sm-10" ng-show = title id ="Table"> <h5>Confirm file to be uploaded and Click the Proceed Button Below</h5> <div id="dvCSV"></div> <br> <button type="button" class="btn btn-success" data-ng-click="add together()">Continue!</button> </div> </div> </div> </form> </div> </div> </div> </div> </section> </torso> </html>
In the code higher up, we utilize the ng-app directive to define our awarding. We and then add together the AngularJS and jQuery libraries to our web page as well as the balance of the script files, i.e. app.js, papaparse.js, and papaparse.min.js.
We and then ascertain the awarding's controller so bind the HTML controls to the awarding data.
Download a CSV File
Since nosotros already accept the interface with the link where a user will be able to download the CSV file, we now proceed to write the Athwart code that will contain the information to be downloaded, then bind it with the HTML controls.
We then make the CSV bachelor for download on the client side.
Inapp.js, initialize the Athwart app and define the CsvCtrl controller.
'use strict'; /* App Module */ var app = athwart.module("myApp", []); Side by side, define the sample data in JSON and catechumen it to a CSV file with the help of the Papa Parse module.
app.controller("CsvCtrl", ["$scope", "$q", part($scope,$q) { var clearAlerts = function() { $scope.mistake = {}, $scope.warning = null }; $scope.download = function(){ var a = document.createElement("a"); var json_pre = '[{"Reference":"one","First_name":"Lauri","Last_name":"Amerman","Dob":"1980","Sex":"F"},{"Reference":"ii","First_name":"Rebbecca","Last_name":"Bellon","Dob":"1977","Sex":"F"},{"Reference":"three","First_name":"Stanley","Last_name":"Benton","Dob":"1984","Sexual activity":"M"}]' var csv = Papa.unparse(json_pre); if (window.navigator.msSaveOrOpenBlob) { var hulk = new Blob([decodeURIComponent(encodeURI(csv))], { type: "text/csv;charset=utf-8;" }); navigator.msSaveBlob(blob, 'sample.csv'); } else { a.href = 'data:zipper/csv;charset=utf-viii,' + encodeURI(csv); a.target = '_blank'; a.download = 'sample.csv'; certificate.torso.appendChild(a); a.click(); } } }]); Uploading and Reading a CSV File
Hither is the Angular office that uploads and reads a CSV file.
app.controller("CsvCtrl", ["$scope", "$q", function($telescopic,$q) { // ... the residuum of the lawmaking // Upload and read CSV function $scope.submitForm = function(form) { clearAlerts(); var filename = document.getElementById("bulkDirectFile"); if (filename.value.length < 1 ){ ($scope.warning = "Please upload a file"); } else { $scope.title = "Confirm file"; var file = filename.files[0]; console.log(file) var fileSize = 0; if (filename.files[0]) { var reader = new FileReader(); reader.onload = part (eastward) { var table = $("<table />").css('width','100%'); var rows = e.target.result.split("\n"); for (var i = 0; i < rows.length; i++) { var row = $("<tr />"); var cells = rows[i].split(","); for (var j = 0; j < cells.length; j++) { var cell = $("<td />").css('border','1px solid black'); prison cell.html(cells[j]); row.append(jail cell); } tabular array.append(row); } $("#dvCSV").html(''); $("#dvCSV").suspend(table); } reader.readAsText(filename.files[0]); } render faux; } } }]); Hither, we confirm if the CSV is valid and not empty. If it is empty or no CSV file has been uploaded, we requite the user a alert message: "Please upload a file." If the CSV is valid, we convert the data to a table format and present it as shown beneath.
Catechumen a CSV File to JSON
In the last part of this tutorial, will be converting the CSV data to JSON format (a form that can be consumed by an API). Below is the function that converts the CSV information to JSON. We will only print the data to the panel since we don't take an API for consuming the data.
app.controller("CsvCtrl", ["$telescopic", "$q", role($scope,$q) { // ... // Convert to JSON function $scope.add = function(){ var Table = document.getElementById('Table'); var file = document.getElementById("bulkDirectFile").files[0]; $('.loading').bear witness(); var allResults = []; Papa.parse(file, { download: true, header: true, skipEmptyLines: true, error: function(err, file, inputElem, reason) { }, consummate: role(results) { allResults.push button(results.information); console.log(results.data) } }); } } }]); In the office higher up, we get the CSV file and utilize Papa Parse to convert it to JSON. The complete code inapp.js is shown below.
Conclusion
In this mail service, you saw how to upload and download CSV data, and how to parse CSV data into and out of JSON.
I hope this tutorial has helped you understand how to dispense CSV files with the Papa Parse module and how powerful that library is. Feel gratuitous to experiment with larger files to encounter the full functionality of the Papa Parse library.
Did you find this mail useful?
Source: https://code.tutsplus.com/tutorials/how-to-upload-and-download-csv-files-with-angularjs--cms-31489
0 Response to "utf-8 Codec Cant Decode Byte 0x89 in Position 323 Invalid Start Byte Angularjs Upload Image"
Post a Comment