ImportService.php 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  1. <?php
  2. namespace App\Service;
  3. use App\Exports\TableHeadExport;
  4. use App\Import\Import;
  5. use App\Import\ImportAll;
  6. use App\Model\BasicType;
  7. use App\Model\Customer;
  8. use App\Model\CustomerInfo;
  9. use App\Model\Depart;
  10. use App\Model\Employee;
  11. use App\Model\Product;
  12. use App\Model\ProductCategory;
  13. use App\Model\ProductPriceDetail;
  14. use App\Model\SalesOrder;
  15. use App\Model\SalesOrderInfo;
  16. use App\Model\SalesOrderProductInfo;
  17. use Illuminate\Support\Facades\DB;
  18. use Illuminate\Support\Facades\Log;
  19. use Illuminate\Support\Facades\Storage;
  20. use Maatwebsite\Excel\Facades\Excel;
  21. use PhpOffice\PhpSpreadsheet\IOFactory;
  22. class ImportService extends Service
  23. {
  24. const tmp_dir = 'upload_occ';
  25. const string = '/api/getFile/';
  26. //文件类型
  27. const FILE_TYPE = [
  28. 'txt',
  29. 'jpg',
  30. 'png',
  31. 'gif',
  32. 'jpeg',
  33. 'zip',
  34. 'rar',
  35. 'xlsx',
  36. 'xls'
  37. ];
  38. //导入入口
  39. public function import($data){
  40. // //不超时
  41. // ini_set('max_execution_time', 0);
  42. // //内存设置
  43. // ini_set('memory_limit', -1);
  44. // $reader = IOFactory::createReader('Xlsx');
  45. // $reader->setReadDataOnly(true); // 只读取有数据的单元格
  46. // $spreadsheet = $reader->load($data['file']);
  47. // dd($spreadsheet);
  48. // // 创建一个Reader对象
  49. // $reader = IOFactory::createReader('Xlsx'); // 根据你的文件格式选择合适的reader
  50. //
  51. //// 加载Excel文件
  52. // $spreadsheet = $reader->load($data['file']);
  53. //
  54. //// 获取第一个工作表
  55. // $worksheet = $spreadsheet->getActiveSheet();
  56. //
  57. //// 获取总行数
  58. // $totalRows = $worksheet->getHighestRow();dd($totalRows);
  59. if(empty($data['file'])) return [false,'导入文件不能为空'];
  60. try {
  61. $this->uploadFile($data['file']);
  62. }catch (\Throwable $exception) {
  63. return [false, $exception->getMessage() . ' (Code: ' . $exception->getCode() . ', Line: ' . $exception->getLine() . ')'];
  64. }
  65. return [true, ''];
  66. }
  67. public function uploadFile($file){
  68. if(empty($file)) return [false, '请上传文件'];
  69. // 获取文件相关信息
  70. $ext = $file->getClientOriginalExtension(); // 扩展名
  71. $realPath = $file->getRealPath(); //临时文件的绝对路径
  72. $ext = strtolower($ext);
  73. if (! in_array($ext, self::FILE_TYPE)){
  74. $str = '文件格式为:';
  75. foreach (self::FILE_TYPE as $value){
  76. $str.= $value . ' ' ;
  77. }
  78. return [false, $str];
  79. }
  80. $date = date("Y-m-d");
  81. //文件名
  82. $file_name = date("Ymd").time().rand(1000,9999);
  83. $filename = $file_name.'.' . $ext;
  84. $dir = self::tmp_dir . '/' . $date . '/' . $filename;
  85. Storage::disk('public')->put($dir, file_get_contents($realPath));
  86. return [true, self::string . $filename];
  87. }
  88. public function getFileData($data){
  89. if(empty($data['url'])) return [false, '文件路径不能为空'];
  90. try{
  91. // 发送 HTTP 请求获取文件内容
  92. $response = file_get_contents($data['url']);
  93. }catch (\Throwable $exception){
  94. return [false, $exception->getMessage()];
  95. }
  96. if ($response === false) return [false, '文件获取失败'];
  97. // 创建一个临时文件资源
  98. $tempFile = tempnam(sys_get_temp_dir(), 'xlsx_');
  99. file_put_contents($tempFile, $response);
  100. // 使用 phpspreadsheet 读取文件
  101. try {
  102. // 创建一个 Xlsx 读取器
  103. $reader = IOFactory::createReader('Xlsx');
  104. // 加载临时文件
  105. $spreadsheet = $reader->load($tempFile);
  106. // 初始化一个数组来存储所有工作表的数据
  107. $allSheetData = [];
  108. // 遍历所有工作表
  109. foreach ($spreadsheet->getWorksheetIterator() as $worksheet) {
  110. $sheetData = [];
  111. foreach ($worksheet->getRowIterator() as $row) {
  112. $cellIterator = $row->getCellIterator();
  113. $cellIterator->setIterateOnlyExistingCells(false); // Loop all cells, even if it is not set
  114. $rowData = [];
  115. foreach ($cellIterator as $cell) {
  116. $rowData[] = $cell->getValue();
  117. }
  118. $sheetData[] = $rowData;
  119. }
  120. // 将当前工作表的数据添加到总数据数组中
  121. $allSheetData[$worksheet->getTitle()] = $sheetData;
  122. }
  123. // 删除临时文件
  124. unlink($tempFile);
  125. } catch (\Exception $e) {
  126. // 删除临时文件
  127. unlink($tempFile);
  128. return [false, $e->getMessage()];
  129. }
  130. return [true , $allSheetData];
  131. }
  132. public function saveFile1($data){
  133. if(empty($data['url'])) return [false, '文件路径不能为空'];
  134. $this->downloadFile($data['url']);
  135. }
  136. public function downloadFile($url)
  137. {
  138. // 发送 HEAD 请求获取响应头
  139. $ch = curl_init();
  140. curl_setopt($ch, CURLOPT_URL, $url);
  141. curl_setopt($ch, CURLOPT_NOBODY, true); // 只获取头部信息
  142. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  143. curl_setopt($ch, CURLOPT_HEADER, true);
  144. curl_setopt($ch, CURLOPT_FAILONERROR, true);
  145. curl_setopt($ch, CURLOPT_TIMEOUT, 30); // 设置超时时间
  146. curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3');
  147. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 忽略 SSL 证书验证(仅用于测试)
  148. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); // 忽略 SSL 主机验证(仅用于测试)
  149. curl_setopt($ch, CURLOPT_VERBOSE, true); // 启用详细调试信息
  150. // 打开一个文件句柄来捕获调试信息
  151. $verbose = fopen('php://temp', 'w+');
  152. curl_setopt($ch, CURLOPT_STDERR, $verbose);
  153. // 执行请求
  154. $response = curl_exec($ch);
  155. $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  156. $error = curl_error($ch);
  157. // 读取调试信息
  158. rewind($verbose);
  159. $verboseLog = stream_get_contents($verbose);
  160. fclose($verbose);
  161. if ($response === false || $httpCode !== 200) {
  162. curl_close($ch);
  163. return [false, '打开URL下的文件内容失败,请更换URL'];
  164. }dd($response);
  165. // 获取 Content-Disposition
  166. $contentDisposition = null;
  167. $headers = explode("\r\n", $response);
  168. foreach ($headers as $headerLine) {
  169. if (strpos($headerLine, 'Content-Disposition:') === 0) {
  170. $contentDisposition = trim(str_replace('Content-Disposition:', '', $headerLine));
  171. break;
  172. }
  173. }dd($headers);
  174. if ($contentDisposition === null) {
  175. curl_close($ch);
  176. return response()->json(['error' => 'Failed to determine file name from Content-Disposition'], 500);
  177. }
  178. // 从 Content-Disposition 中提取文件名
  179. preg_match('/fileName="?([^"]+)"?/', $contentDisposition, $matches);
  180. if (empty($matches)) {
  181. curl_close($ch);
  182. return response()->json(['error' => 'Failed to extract file name from Content-Disposition'], 500);
  183. }
  184. $filename = urldecode($matches[1]);
  185. $extension = pathinfo($filename, PATHINFO_EXTENSION);
  186. dd($extension);
  187. if ($extension === '') {
  188. curl_close($ch);
  189. return response()->json(['error' => 'Failed to determine file extension'], 500);
  190. }
  191. // 关闭 cURL 资源
  192. curl_close($ch);
  193. // 发送 GET 请求获取文件内容
  194. $ch = curl_init();
  195. curl_setopt($ch, CURLOPT_URL, $url);
  196. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  197. curl_setopt($ch, CURLOPT_FAILONERROR, true);
  198. curl_setopt($ch, CURLOPT_TIMEOUT, 30); // 设置超时时间
  199. curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3');
  200. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 忽略 SSL 证书验证(仅用于测试)
  201. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); // 忽略 SSL 主机验证(仅用于测试)
  202. // 执行请求
  203. $response = curl_exec($ch);
  204. $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  205. $error = curl_error($ch);
  206. if ($response === false || $httpCode !== 200) {
  207. curl_close($ch);
  208. return response()->json(['error' => 'Failed to download file: HTTP status code ' . $httpCode . ', Error: ' . $error], 500);
  209. }
  210. // 关闭 cURL 资源
  211. curl_close($ch);
  212. // 将文件内容保存到本地存储
  213. Storage::put($filename, $response);
  214. return response()->json(['message' => 'File downloaded and saved successfully', 'file' => $filename]);
  215. }
  216. private function getFileTypeExtension($contentType)
  217. {
  218. $mimeTypeMap = [
  219. 'application/pdf' => 'pdf',
  220. 'application/msword' => 'doc',
  221. 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' => 'docx',
  222. 'application/vnd.ms-excel' => 'xls',
  223. 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' => 'xlsx',
  224. 'image/jpeg' => 'jpg',
  225. 'image/png' => 'png',
  226. 'image/gif' => 'gif',
  227. 'text/plain' => 'txt',
  228. // 添加其他 MIME 类型和扩展名映射
  229. ];
  230. return isset($mimeTypeMap[$contentType]) ? $mimeTypeMap[$contentType] : null;
  231. }
  232. }