123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278 |
- <?php
- namespace App\Service;
- use App\Exports\TableHeadExport;
- use App\Import\Import;
- use App\Import\ImportAll;
- use App\Model\BasicType;
- use App\Model\Customer;
- use App\Model\CustomerInfo;
- use App\Model\Depart;
- use App\Model\Employee;
- use App\Model\Product;
- use App\Model\ProductCategory;
- use App\Model\ProductPriceDetail;
- use App\Model\SalesOrder;
- use App\Model\SalesOrderInfo;
- use App\Model\SalesOrderProductInfo;
- use Illuminate\Support\Facades\DB;
- use Illuminate\Support\Facades\Log;
- use Illuminate\Support\Facades\Storage;
- use Maatwebsite\Excel\Facades\Excel;
- use PhpOffice\PhpSpreadsheet\IOFactory;
- class ImportService extends Service
- {
- const tmp_dir = 'upload_occ';
- const string = '/api/getFile/';
- //文件类型
- const FILE_TYPE = [
- 'txt',
- 'jpg',
- 'png',
- 'gif',
- 'jpeg',
- 'zip',
- 'rar',
- 'xlsx',
- 'xls'
- ];
- //导入入口
- public function import($data){
- // //不超时
- // ini_set('max_execution_time', 0);
- // //内存设置
- // ini_set('memory_limit', -1);
- // $reader = IOFactory::createReader('Xlsx');
- // $reader->setReadDataOnly(true); // 只读取有数据的单元格
- // $spreadsheet = $reader->load($data['file']);
- // dd($spreadsheet);
- // // 创建一个Reader对象
- // $reader = IOFactory::createReader('Xlsx'); // 根据你的文件格式选择合适的reader
- //
- //// 加载Excel文件
- // $spreadsheet = $reader->load($data['file']);
- //
- //// 获取第一个工作表
- // $worksheet = $spreadsheet->getActiveSheet();
- //
- //// 获取总行数
- // $totalRows = $worksheet->getHighestRow();dd($totalRows);
- if(empty($data['file'])) return [false,'导入文件不能为空'];
- try {
- $this->uploadFile($data['file']);
- }catch (\Throwable $exception) {
- return [false, $exception->getMessage() . ' (Code: ' . $exception->getCode() . ', Line: ' . $exception->getLine() . ')'];
- }
- return [true, ''];
- }
- public function uploadFile($file){
- if(empty($file)) return [false, '请上传文件'];
- // 获取文件相关信息
- $ext = $file->getClientOriginalExtension(); // 扩展名
- $realPath = $file->getRealPath(); //临时文件的绝对路径
- $ext = strtolower($ext);
- if (! in_array($ext, self::FILE_TYPE)){
- $str = '文件格式为:';
- foreach (self::FILE_TYPE as $value){
- $str.= $value . ' ' ;
- }
- return [false, $str];
- }
- $date = date("Y-m-d");
- //文件名
- $file_name = date("Ymd").time().rand(1000,9999);
- $filename = $file_name.'.' . $ext;
- $dir = self::tmp_dir . '/' . $date . '/' . $filename;
- Storage::disk('public')->put($dir, file_get_contents($realPath));
- return [true, self::string . $filename];
- }
- public function getFileData($data){
- if(empty($data['url'])) return [false, '文件路径不能为空'];
- try{
- // 发送 HTTP 请求获取文件内容
- $response = file_get_contents($data['url']);
- }catch (\Throwable $exception){
- return [false, $exception->getMessage()];
- }
- if ($response === false) return [false, '文件获取失败'];
- // 创建一个临时文件资源
- $tempFile = tempnam(sys_get_temp_dir(), 'xlsx_');
- file_put_contents($tempFile, $response);
- // 使用 phpspreadsheet 读取文件
- try {
- // 创建一个 Xlsx 读取器
- $reader = IOFactory::createReader('Xlsx');
- // 加载临时文件
- $spreadsheet = $reader->load($tempFile);
- // 初始化一个数组来存储所有工作表的数据
- $allSheetData = [];
- // 遍历所有工作表
- foreach ($spreadsheet->getWorksheetIterator() as $worksheet) {
- $sheetData = [];
- foreach ($worksheet->getRowIterator() as $row) {
- $cellIterator = $row->getCellIterator();
- $cellIterator->setIterateOnlyExistingCells(false); // Loop all cells, even if it is not set
- $rowData = [];
- foreach ($cellIterator as $cell) {
- $rowData[] = $cell->getValue();
- }
- $sheetData[] = $rowData;
- }
- // 将当前工作表的数据添加到总数据数组中
- $allSheetData[$worksheet->getTitle()] = $sheetData;
- }
- // 删除临时文件
- unlink($tempFile);
- } catch (\Exception $e) {
- // 删除临时文件
- unlink($tempFile);
- return [false, $e->getMessage()];
- }
- return [true , $allSheetData];
- }
- public function saveFile1($data){
- if(empty($data['url'])) return [false, '文件路径不能为空'];
- $this->downloadFile($data['url']);
- }
- public function downloadFile($url)
- {
- // 发送 HEAD 请求获取响应头
- $ch = curl_init();
- curl_setopt($ch, CURLOPT_URL, $url);
- curl_setopt($ch, CURLOPT_NOBODY, true); // 只获取头部信息
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
- curl_setopt($ch, CURLOPT_HEADER, true);
- curl_setopt($ch, CURLOPT_FAILONERROR, true);
- curl_setopt($ch, CURLOPT_TIMEOUT, 30); // 设置超时时间
- 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');
- curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 忽略 SSL 证书验证(仅用于测试)
- curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); // 忽略 SSL 主机验证(仅用于测试)
- curl_setopt($ch, CURLOPT_VERBOSE, true); // 启用详细调试信息
- // 打开一个文件句柄来捕获调试信息
- $verbose = fopen('php://temp', 'w+');
- curl_setopt($ch, CURLOPT_STDERR, $verbose);
- // 执行请求
- $response = curl_exec($ch);
- $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
- $error = curl_error($ch);
- // 读取调试信息
- rewind($verbose);
- $verboseLog = stream_get_contents($verbose);
- fclose($verbose);
- if ($response === false || $httpCode !== 200) {
- curl_close($ch);
- return [false, '打开URL下的文件内容失败,请更换URL'];
- }dd($response);
- // 获取 Content-Disposition
- $contentDisposition = null;
- $headers = explode("\r\n", $response);
- foreach ($headers as $headerLine) {
- if (strpos($headerLine, 'Content-Disposition:') === 0) {
- $contentDisposition = trim(str_replace('Content-Disposition:', '', $headerLine));
- break;
- }
- }dd($headers);
- if ($contentDisposition === null) {
- curl_close($ch);
- return response()->json(['error' => 'Failed to determine file name from Content-Disposition'], 500);
- }
- // 从 Content-Disposition 中提取文件名
- preg_match('/fileName="?([^"]+)"?/', $contentDisposition, $matches);
- if (empty($matches)) {
- curl_close($ch);
- return response()->json(['error' => 'Failed to extract file name from Content-Disposition'], 500);
- }
- $filename = urldecode($matches[1]);
- $extension = pathinfo($filename, PATHINFO_EXTENSION);
- dd($extension);
- if ($extension === '') {
- curl_close($ch);
- return response()->json(['error' => 'Failed to determine file extension'], 500);
- }
- // 关闭 cURL 资源
- curl_close($ch);
- // 发送 GET 请求获取文件内容
- $ch = curl_init();
- curl_setopt($ch, CURLOPT_URL, $url);
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
- curl_setopt($ch, CURLOPT_FAILONERROR, true);
- curl_setopt($ch, CURLOPT_TIMEOUT, 30); // 设置超时时间
- 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');
- curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 忽略 SSL 证书验证(仅用于测试)
- curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); // 忽略 SSL 主机验证(仅用于测试)
- // 执行请求
- $response = curl_exec($ch);
- $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
- $error = curl_error($ch);
- if ($response === false || $httpCode !== 200) {
- curl_close($ch);
- return response()->json(['error' => 'Failed to download file: HTTP status code ' . $httpCode . ', Error: ' . $error], 500);
- }
- // 关闭 cURL 资源
- curl_close($ch);
- // 将文件内容保存到本地存储
- Storage::put($filename, $response);
- return response()->json(['message' => 'File downloaded and saved successfully', 'file' => $filename]);
- }
- private function getFileTypeExtension($contentType)
- {
- $mimeTypeMap = [
- 'application/pdf' => 'pdf',
- 'application/msword' => 'doc',
- 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' => 'docx',
- 'application/vnd.ms-excel' => 'xls',
- 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' => 'xlsx',
- 'image/jpeg' => 'jpg',
- 'image/png' => 'png',
- 'image/gif' => 'gif',
- 'text/plain' => 'txt',
- // 添加其他 MIME 类型和扩展名映射
- ];
- return isset($mimeTypeMap[$contentType]) ? $mimeTypeMap[$contentType] : null;
- }
- }
|