Mysql
 sql >> Base de Dados >  >> RDS >> Mysql

Como usar o AJAX para fazer upload de um arquivo CSV grande?


Depois de fazer algumas pesquisas na web, descobri que o HTML5 JavaScript File API é muito útil para ler o conteúdo do sistema de arquivos local. Eu escrevi um pequeno script e está funcionando perfeitamente.

Para este exemplo, criei dois arquivos -
  1. index.htm
  2. serviço.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>

serviço.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
    //----
}