sql >> Base de Datos >  >> RDS >> Mysql

¿Cómo usar AJAX para cargar un archivo CSV grande?

Después de investigar un poco en la web, descubrí que HTML5 JavaScript File API es muy útil para leer contenido del sistema de archivos local. He escrito un pequeño script y funciona perfectamente.

Para este ejemplo, he creado dos archivos -

  1. index.htm
  2. servicio.php

index.htm

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>Upload large CSV file</title>
		<style>
			body{font-size:8pt; color:#333}
			#wrap{width:500px; margin:5px auto}
			#responce{height:200px; overflow-y:scroll; border:1px solid #ddd;}
		</style>
	</head>

	<body>
		<div id="wrap">
			<ul id="responce">
				
			</ul><!-- // response -->
			
			<input type="file" id="fileSelected"/>
			<button id="btnUpload">Upload</button>
		</div><!-- // wrap -->
		
		<script
			  src="https://code.jquery.com/jquery-3.1.1.min.js"
			  integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8="
			  crossorigin="anonymous"></script>
		<script>
			var reader_offset = 0;		//current reader offset position
			var buffer_size = 1024;		//
			var pending_content = '';
			
			/**
			* Read a chunk of data from current offset.
			*/
			function readAndSendChunk()
			{
				var reader = new FileReader();
				var file = $('#fileSelected')[0].files[0];
				reader.onloadend = function(evt){
					
					//check for end of file
					if(evt.loaded == 0) return;
					
					//increse offset value
					reader_offset += evt.loaded;
					
					//check for only complete line
					var last_line_end = evt.target.result.lastIndexOf('\n');
					var content = pending_content + evt.target.result.substring(0, last_line_end);
					
					pending_content = evt.target.result.substring(last_line_end+1, evt.target.result.length);
					
					//upload data
					send(content);
				};
				var blob = file.slice(reader_offset, reader_offset + buffer_size);
				reader.readAsText(blob);
			}
			
			/**
			* Send data to server using AJAX
			*/
			function send(data_chank)
			{
				$.ajax({
					url: "service.php",
					method: 'POST',
					data: data_chank
				}).done(function(response) {
				
					//show responce message received from server
					$( '#responce' ).append( '<li>' + response + '</li>');
					
					//try for next chank
					readAndSendChunk();
				});
			}
			
			/**
			* On page load
			*/
			$(function(){
				$('#btnUpload').click(function(){
					reader_offset = 0;
					pending_content = '';
					readAndSendChunk();
				});
			});
		</script>
	</body>
</html>

servicio.php

<?php
$content = file_get_contents('php://input');
$lines = explode("\n", $content);
foreach($lines as $line){
    $csv_row = str_getcsv($line);
    //save data into database
    //----
}