Files
bsh_sample/app/admin/controller/SkuController.php
T

630 lines
21 KiB
PHP
Raw Normal View History

2025-12-08 17:37:34 +08:00
<?php
namespace app\admin\controller;
use app\common\controller\BaseController;
2025-12-11 17:25:10 +08:00
use app\common\model\PostCategory;
2025-12-13 16:35:34 +08:00
use app\common\model\Sku;
2025-12-13 10:48:51 +08:00
use app\common\model\SkuAttribute;
2025-12-11 14:17:24 +08:00
use app\common\service\OssService;
2025-12-15 14:07:07 +08:00
use app\common\service\UploadService;
2025-12-08 17:37:34 +08:00
use app\common\traits\crud\CrudControllerTrait;
use app\common\service\SkuService;
2025-12-13 16:35:34 +08:00
use PhpOffice\PhpSpreadsheet\IOFactory;
2025-12-16 10:16:25 +08:00
use PhpOffice\PhpWord\IOFactory as WordIOFactory;
2025-12-13 16:35:34 +08:00
use PhpOffice\PhpSpreadsheet\Worksheet\Drawing;
use support\Db;
2025-12-09 15:33:21 +08:00
use support\Request;
2025-12-13 16:35:34 +08:00
use support\Response;
2025-12-16 10:16:25 +08:00
use ZipArchive;
2025-12-08 17:37:34 +08:00
class SkuController extends BaseController
{
use CrudControllerTrait;
2025-12-13 16:35:34 +08:00
protected $noNeedLogin = ['template'];
protected $noNeedHeaderData = ['template'];
2025-12-08 17:37:34 +08:00
protected $service;
public function __construct()
{
$this->service = new SkuService();
}
2025-12-09 15:33:21 +08:00
/**
* 创建
*
* @param Request $request 请求对象
* @return mixed 返回创建成功的数据或信息
*/
public function store(Request $request)
{
try {
$data = $this->validate($this->service->getValidator(), $request->post(), 'store');
$res = $this->service->serviceStore($request, $data);
return $this->success($res, '创建成功');
} catch (\Throwable $e) {
2025-12-11 14:17:24 +08:00
return $this->error($e->getMessage());
2025-12-09 15:33:21 +08:00
}
}
2025-12-08 17:37:34 +08:00
/**
* 列表页数据格式化
*
* @param array $data
* @return array
*/
2025-12-09 15:33:21 +08:00
protected function indexFormat($data)
{
if (isset($data['created_at']))
$data['created_at'] = date('Y-m-d H:i:s', $data['created_at']);
if (isset($data['updated_at']))
$data['updated_at'] = date('Y-m-d H:i:s', $data['updated_at']);
2025-12-13 10:48:51 +08:00
if (isset($data['spec_json'])){
2025-12-10 14:59:41 +08:00
$data['spec'] = json_decode($data['spec_json'], true);
2025-12-13 10:48:51 +08:00
foreach ($data['spec'] as $k=>$v){
2025-12-23 09:43:51 +08:00
$skuAttribute = SkuAttribute::where('category_id',$data['category_id'])
->where('attr_name', $v['attr_name'])->first();
if ($skuAttribute){
$data['spec'][$k]['attr_id'] = $skuAttribute['id'];
$data['spec'][$k]['attr_type'] = $skuAttribute['attr_type'];
}else{
$data['spec'][$k]['attr_type'] = SkuAttribute::where('id', $v['attr_id'])->value('attr_type');
}
2025-12-31 15:56:47 +08:00
if($data['spec'][$k]['attr_type'] == 'multiselect'){
$data['spec'][$k]['attr_value'] = str_replace([',', ',', ' '], ',', $v['attr_value']);
}
2025-12-13 10:48:51 +08:00
}
}
2025-12-11 17:25:10 +08:00
if (isset($data['category_id']))
$data['category_name'] = PostCategory::where('id', $data['category_id'])->value('name');
2025-12-11 14:17:24 +08:00
$ossservice = new OssService();
2025-12-12 14:15:24 +08:00
if (!empty($data['image'])){
2025-12-11 14:17:24 +08:00
$data['image'] = explode(',',$data['image']);
foreach ($data['image'] as $key => $image){
$data['image_pull'][$key] = $ossservice->generatePrivateUrl($image);
}
2025-12-12 14:15:24 +08:00
}else{
$data['image'] = [];
$data['image_pull'] = [];
2025-12-11 14:17:24 +08:00
}
2025-12-12 14:15:24 +08:00
if (!empty($data['main_image'])){
2025-12-11 14:17:24 +08:00
$data['main_image_pull'] = $ossservice->generatePrivateUrl($data['main_image']);
2025-12-12 14:15:24 +08:00
} else {
$data['main_image_pull'] = [];
}
2025-12-09 15:33:21 +08:00
return $data;
}
2025-12-13 16:35:34 +08:00
public function import(Request $request)
{
2025-12-22 16:01:11 +08:00
// ini_set('memory_limit', '512M');
2025-12-13 16:35:34 +08:00
$file = $request->file('file');
2025-12-16 13:30:21 +08:00
if (!$file) return $this->error('未上传文件');;
2025-12-13 16:35:34 +08:00
2025-12-16 10:16:25 +08:00
$zipPath = runtime_path('upload/' . uniqid() . '.zip');
$file->move($zipPath);
2025-12-16 10:25:37 +08:00
$extractTo = runtime_path('upload/import/');
2025-12-16 13:30:21 +08:00
clearstatcache(true, $zipPath);
2025-12-16 10:16:25 +08:00
$this->unzipPackage($zipPath,$extractTo);
2025-12-13 16:35:34 +08:00
2025-12-16 10:16:25 +08:00
$path = runtime_path('upload/import/product.xlsx');
2025-12-13 16:35:34 +08:00
$spreadsheet = IOFactory::load($path);
$sheet = $spreadsheet->getActiveSheet();
// 提取图片(按行号)
2025-12-16 10:16:25 +08:00
//$rowImages = $this->extractImages($sheet);
2025-12-13 16:35:34 +08:00
$highestRow = $sheet->getHighestRow();
$highestCol = $sheet->getHighestColumn();
$header = $sheet->rangeToArray("A1:{$highestCol}1")[0];
2025-12-13 17:31:15 +08:00
// $header = array_map('trim', $header);
2025-12-13 16:35:34 +08:00
$allowFields = [
'product_name' => '产品名称',
'model' => '产品型号',
'brand' => '品牌',
'category_id' => '分类',
'price' => '价格',
2025-12-16 10:16:25 +08:00
//'spec_json' => '商品属性'
2025-12-13 16:35:34 +08:00
];
$fieldsName = array_flip($allowFields);
2025-12-22 11:32:07 +08:00
$attributeFields = [
2025-12-31 15:56:47 +08:00
'外观' => '外观',
2025-12-23 13:52:02 +08:00
'产品尺寸(宽*高*深)' => '产品尺寸(宽*高*深)',
'开孔尺寸(宽*高*深)' => '开孔尺寸(宽*高*深)',
2025-12-22 16:01:11 +08:00
'容积' => '容积',
2025-12-31 15:56:47 +08:00
'产品卖点' => '产品卖点',
2025-12-22 11:32:07 +08:00
];
$attributeFieldsName = array_flip($attributeFields);
2025-12-13 16:35:34 +08:00
$insertData = [];
$now = time();
Db::beginTransaction();
2025-12-16 10:16:25 +08:00
$uploadService = new UploadService();
2025-12-13 16:35:34 +08:00
try {
for ($row = 2; $row <= $highestRow; $row++) {
$rowData = $sheet->rangeToArray(
"A{$row}:{$highestCol}{$row}", null, true, false
)[0];
$data = [];
2025-12-22 11:32:07 +08:00
$attributes = [];
2025-12-13 16:35:34 +08:00
foreach ($header as $i => $field) {
if (in_array($field, $allowFields)) {
$data[$fieldsName[$field]] = trim((string)($rowData[$i] ?? ''));
}
2025-12-22 11:32:07 +08:00
//商品属性
2025-12-22 16:01:11 +08:00
if (in_array($field, $attributeFields) && !empty($rowData[$i])) {
2025-12-22 11:32:07 +08:00
$attributes[$attributeFieldsName[$field]] = trim((string)($rowData[$i] ?? ''));
}
2025-12-13 16:35:34 +08:00
}
if (empty($data['product_name'])) {
continue;
}
2025-12-22 16:01:11 +08:00
$data['category_id'] = PostCategory::where('name', $rowData[4])->value('id')??0;
2025-12-22 11:32:07 +08:00
2025-12-22 16:01:11 +08:00
$spec = [];
2025-12-22 11:32:07 +08:00
foreach ($attributes as $key => $attribute) {
$skuAttribute = SkuAttribute::where('category_id',$data['category_id'])
->where('attr_name', $key)
2025-12-22 16:01:11 +08:00
->first();
2025-12-22 11:32:07 +08:00
if (empty($skuAttribute)) {
$skuAttribute = SkuAttribute::create([
'category_id' => $data['category_id'],
'attr_name' => $key,
'attr_type' => 'text',
]);
}
$attr = ['attr_name' => $key,'attr_value'=> $attribute];
$attr['attr_id'] = $skuAttribute->id;
$attr['category_id'] = $data['category_id'];
// $spec = ['sku_id' => $skuAttribute->id];
$spec[] = $attr;
}
2025-12-22 16:01:11 +08:00
$data['spec_json'] = json_encode($spec);
2025-12-16 10:16:25 +08:00
//商品属性
2025-12-22 16:01:11 +08:00
// if(!empty($rowData[5])){
// $speci = explode(';', $rowData[5]);
// $spec = [];
// foreach ($speci as $k => $v){
// $item = explode(':', $v);
// if (count($item) != 2) {
// continue;
// }
// $attr = ['attr_name'=>$item[0],'attr_value'=>$item[1]];
// $skuAttribute = SkuAttribute::where('attr_name', $item[0])
// ->where('category_id', $data['category_id'])->first();
// if (empty($skuAttribute)) {
// $skuAttribute = SkuAttribute::create([
// 'attr_name' => $item[0],
// 'attr_value' => $item[1],
// 'category_id' => $data['category_id'],
// 'attr_type' => 'text'
// ]);
// }
// $attr['attr_id'] = $skuAttribute->id;
// $attr['category_id'] = $data['category_id'];
// $spec[] = $attr;
// $data['spec_json'] = json_encode($spec);
// }
// }
2025-12-13 16:35:34 +08:00
2025-12-16 10:16:25 +08:00
//主图
2025-12-22 16:01:11 +08:00
if(!empty($rowData[7])){
$tmpPath = runtime_path('upload/import/pic/'.$rowData[7]);
2025-12-16 10:16:25 +08:00
$res = $uploadService->uploadLocalFile(['path' => $tmpPath, 'scene' => 'sku']);
2025-12-16 13:30:21 +08:00
$data['main_image'] = $res['file_name'];
2025-12-16 10:16:25 +08:00
}
//详情
2025-12-22 16:01:11 +08:00
if(!empty($rowData[8])){
$docxFullPath = runtime_path('upload/import/docs/'.$rowData[8]);
2025-12-16 13:30:21 +08:00
if (filesize($docxFullPath) !== 0 && file_exists($zipPath)) {
$data['desc'] =$this->docxToHtmlWithImages($docxFullPath);
}
//$data['desc'] =$this->docxToHtmlWithImages($docxFullPath);
2025-12-16 10:16:25 +08:00
}
2025-12-13 16:35:34 +08:00
$data['code'] = $this->service->generateUniqueCode();
$data['brand'] = $data['brand'] ?: '西门子';
$data['price'] = $data['price'] ?: 0;
2025-12-16 13:47:19 +08:00
$data['status'] = $data['status'] ?? 1;
2025-12-13 16:35:34 +08:00
// 图片
2025-12-16 10:16:25 +08:00
//$data['main_image'] = $rowImages[$row] ?? null;
2025-12-13 16:35:34 +08:00
$data['created_at'] = $now;
$data['updated_at'] = $now;
$insertData[] = $data;
if (count($insertData) >= 200) {
Sku::insert($insertData);
// Db::table('sku')->insert($insertData);
$insertData = [];
}
}
2025-12-31 15:56:47 +08:00
@unlink($zipPath);
2025-12-13 16:35:34 +08:00
if ($insertData) {
Sku::insert($insertData);
// Db::table('sku')->insert($insertData);
}
Db::commit();
} catch (\Throwable $e) {
Db::rollBack();
2025-12-16 10:27:22 +08:00
return $this->error($e->getMessage().$e->getLine().$e->getFile());
2025-12-13 16:35:34 +08:00
} finally {
@unlink($path);
}
return $this->success([], '导入成功');
}
2025-12-16 10:16:25 +08:00
/**
* 解压 zip 文件
*
* @param string $zipPath zip 文件绝对路径
* @param string $extractTo 解压目录
* @return bool
*/
function unzipPackage(string $zipPath, string $extractTo): bool
{
if (!file_exists($zipPath)) {
throw new \Exception('ZIP 文件不存在');
}
if (!is_dir($extractTo)) {
mkdir($extractTo, 0755, true);
}
$zip = new ZipArchive();
if ($zip->open($zipPath) !== true) {
throw new \Exception('ZIP 文件打开失败');
}
$zip->extractTo($extractTo);
$zip->close();
return true;
}
2025-12-16 14:34:09 +08:00
/**
2025-12-16 15:42:51 +08:00
* docx 转 HTML(富文本可用,图片上传 OSS)
2025-12-16 14:34:09 +08:00
*/
function docxToHtmlWithImages(string $docxPath): string
{
if (!is_file($docxPath)) {
return '';
}
2025-12-16 15:52:18 +08:00
$phpWord = \PhpOffice\PhpWord\IOFactory::load($docxPath);
2025-12-16 15:37:34 +08:00
2025-12-16 15:42:51 +08:00
$tmpDir = runtime_path('tmp/' . uniqid());
if (!is_dir($tmpDir)) {
mkdir($tmpDir, 0755, true);
}
2025-12-16 15:37:34 +08:00
2025-12-16 15:42:51 +08:00
$tmpHtml = $tmpDir . '/index.html';
2025-12-16 15:37:34 +08:00
2025-12-16 15:52:18 +08:00
$writer = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'HTML');
2025-12-16 15:42:51 +08:00
$writer->save($tmpHtml);
2025-12-16 15:37:34 +08:00
2025-12-16 15:42:51 +08:00
$html = file_get_contents($tmpHtml);
2025-12-16 15:37:34 +08:00
2025-12-16 15:52:18 +08:00
// 1️⃣ 上传图片到 OSS
2025-12-16 15:42:51 +08:00
$uploadService = new UploadService();
$html = preg_replace_callback(
'/<img[^>]+src="([^"]+)"[^>]*>/i',
2025-12-16 15:52:18 +08:00
function ($m) use ($tmpDir, $uploadService) {
$src = $m[1];
if (!str_starts_with($src, 'http')) {
$localImg = $tmpDir . '/' . ltrim($src, './');
if (is_file($localImg)) {
$ossUrl = $uploadService->uploadLocalFile([
'path' => $localImg,
'scene' => 'desc'
]);
return preg_replace('/src="[^"]+"/', 'src="'.$ossUrl.'"', $m[0]);
}
2025-12-16 15:37:34 +08:00
}
2025-12-16 15:52:18 +08:00
return $m[0];
2025-12-16 15:42:51 +08:00
},
$html
);
2025-12-16 15:37:34 +08:00
2025-12-16 15:52:18 +08:00
// 2️⃣ 关键:HTML 清洗(适配 wangEditor)
$html = $this->cleanWordHtmlForWangEditor($html);
2025-12-16 15:42:51 +08:00
$this->deleteDir($tmpDir);
2025-12-16 15:52:18 +08:00
return $html;
}
function cleanWordHtmlForWangEditor(string $html): string
{
// 1. 移除 Word 专属标签
$html = preg_replace('/<o:p>.*?<\/o:p>/is', '', $html);
$html = preg_replace('/<\/?xml[^>]*>/i', '', $html);
$html = preg_replace('/<\/?v:[^>]*>/i', '', $html);
// 2. 移除 class / style
$html = preg_replace('/\sclass="[^"]*"/i', '', $html);
$html = preg_replace('/\sstyle="[^"]*"/i', '', $html);
// 3. 清理 span(保留内容)
while (preg_match('/<span[^>]*>(.*?)<\/span>/is', $html)) {
$html = preg_replace('/<span[^>]*>(.*?)<\/span>/is', '$1', $html);
}
// 4. 转换 div → p
$html = preg_replace('/<div[^>]*>/i', '<p>', $html);
$html = preg_replace('/<\/div>/i', '</p>', $html);
// 5. img 只保留 src
$html = preg_replace('/<img[^>]*src="([^"]+)"[^>]*>/i', '<img src="$1">', $html);
// 6. table 清洗
$html = preg_replace('/<table[^>]*>/i', '<table>', $html);
$html = preg_replace('/<td[^>]*>/i', '<td>', $html);
$html = preg_replace('/<th[^>]*>/i', '<th>', $html);
// 7. 去除多余空白
$html = preg_replace('/\s+/u', ' ', $html);
$html = str_replace(['<p></p>', '<p> </p>'], '', $html);
2025-12-16 16:02:33 +08:00
// 只保留 body 内容
if (preg_match('/<body[^>]*>(.*?)<\/body>/is', $html, $m)) {
2025-12-16 16:08:24 +08:00
$html = $m[1];
}
2025-12-16 15:42:51 +08:00
return trim($html);
2025-12-16 15:37:34 +08:00
}
2025-12-16 15:52:18 +08:00
2025-12-16 15:42:51 +08:00
function cleanWordHtml(string $html): string
2025-12-16 15:37:34 +08:00
{
2025-12-16 15:42:51 +08:00
// 删除 Word 注释
$html = preg_replace('/<!--(.|\s)*?-->/', '', $html);
2025-12-16 15:37:34 +08:00
2025-12-16 15:42:51 +08:00
// 删除 style / meta / link
$html = preg_replace('/<(style|meta|link)[^>]*>.*?<\/\1>/is', '', $html);
2025-12-16 15:37:34 +08:00
2025-12-16 15:42:51 +08:00
// 删除 xml 标签
$html = preg_replace('/<xml>.*?<\/xml>/is', '', $html);
2025-12-16 15:37:34 +08:00
2025-12-16 15:42:51 +08:00
// 删除 mso-xxx 样式
$html = preg_replace('/\s*mso-[^:]+:[^;"]+;?/i', '', $html);
2025-12-16 15:37:34 +08:00
2025-12-16 15:42:51 +08:00
// 清理 class="Mso..."
$html = preg_replace('/class="Mso[^"]*"/i', '', $html);
2025-12-16 15:37:34 +08:00
2025-12-16 15:42:51 +08:00
// 删除空 span
$html = preg_replace('/<span[^>]*>\s*<\/span>/i', '', $html);
2025-12-16 15:37:34 +08:00
2025-12-16 15:42:51 +08:00
// 删除 Office 条件注释
$html = preg_replace('/<!\[if.*?\]>.*?<!\[endif\]>/is', '', $html);
2025-12-16 15:37:34 +08:00
2025-12-16 15:42:51 +08:00
// 只保留 body 内容
if (preg_match('/<body[^>]*>(.*?)<\/body>/is', $html, $m)) {
$html = $m[1];
2025-12-16 15:37:34 +08:00
}
2025-12-16 16:11:29 +08:00
//限制图片宽度(防止编辑器撑爆)
$html = preg_replace(
'/<img([^>]+)>/i',
'<img$1 style="max-width:100%;">',
$html
);
2025-12-16 15:42:51 +08:00
return $html;
2025-12-16 15:37:34 +08:00
}
/**
* docx 转 HTML(富文本可用,图片上传 OSS)
*/
/*function docxToHtmlWithImages(string $docxPath): string
{
if (!is_file($docxPath)) {
return '';
}
2025-12-16 14:59:13 +08:00
$phpWord = \PhpOffice\PhpWord\IOFactory::load($docxPath);
2025-12-16 14:34:09 +08:00
$tmpDir = runtime_path('tmp/' . uniqid());
if (!is_dir($tmpDir)) {
mkdir($tmpDir, 0755, true);
}
$tmpHtml = $tmpDir . '/index.html';
2025-12-16 14:59:13 +08:00
$writer = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'HTML');
2025-12-16 14:34:09 +08:00
$writer->save($tmpHtml);
$html = file_get_contents($tmpHtml);
2025-12-16 14:59:13 +08:00
// 1️⃣ 上传图片到 OSS
2025-12-16 14:34:09 +08:00
$uploadService = new UploadService();
$html = preg_replace_callback(
'/<img[^>]+src="([^"]+)"[^>]*>/i',
2025-12-16 14:59:13 +08:00
function ($m) use ($tmpDir, $uploadService) {
$src = $m[1];
2025-12-16 14:34:09 +08:00
2025-12-16 14:48:18 +08:00
if (!str_starts_with($src, 'http')) {
2025-12-16 14:59:13 +08:00
$localImg = $tmpDir . '/' . ltrim($src, './');
2025-12-16 14:48:18 +08:00
if (is_file($localImg)) {
$ossUrl = $uploadService->uploadLocalFile([
2025-12-16 14:59:13 +08:00
'path' => $localImg,
2025-12-16 14:48:18 +08:00
'scene' => 'desc'
]);
2025-12-16 14:59:13 +08:00
return preg_replace('/src="[^"]+"/', 'src="'.$ossUrl['file_url'].'"', $m[0]);
2025-12-16 14:48:18 +08:00
}
2025-12-16 14:34:09 +08:00
}
2025-12-16 14:59:13 +08:00
return $m[0];
2025-12-16 14:34:09 +08:00
},
$html
);
2025-12-16 15:10:32 +08:00
// // 2️⃣ 关键:HTML 清洗(适配 wangEditor)
2025-12-16 15:37:34 +08:00
$html = $this->cleanWordHtmlForWangEditor($html);
2025-12-16 14:34:09 +08:00
2025-12-16 14:59:13 +08:00
return $html;
2025-12-16 15:37:34 +08:00
}*/
2025-12-16 14:34:09 +08:00
2025-12-16 14:48:18 +08:00
function deleteDir(string $dir): void
2025-12-16 14:34:09 +08:00
{
if (!is_dir($dir)) return;
foreach (scandir($dir) as $file) {
if ($file === '.' || $file === '..') continue;
$path = $dir . '/' . $file;
2025-12-16 14:59:13 +08:00
is_dir($path) ? $this->deleteDir($path) : @unlink($path);
2025-12-16 14:34:09 +08:00
}
2025-12-16 14:48:18 +08:00
@rmdir($dir);
2025-12-16 14:34:09 +08:00
}
2025-12-16 15:57:44 +08:00
/*function cleanWordHtmlForWangEditor(string $html): string
2025-12-16 14:34:09 +08:00
{
2025-12-16 14:59:13 +08:00
// 1. 移除 Word 专属标签
$html = preg_replace('/<o:p>.*?<\/o:p>/is', '', $html);
$html = preg_replace('/<\/?xml[^>]*>/i', '', $html);
$html = preg_replace('/<\/?v:[^>]*>/i', '', $html);
// 2. 移除 class / style
$html = preg_replace('/\sclass="[^"]*"/i', '', $html);
$html = preg_replace('/\sstyle="[^"]*"/i', '', $html);
// 3. 清理 span(保留内容)
while (preg_match('/<span[^>]*>(.*?)<\/span>/is', $html)) {
$html = preg_replace('/<span[^>]*>(.*?)<\/span>/is', '$1', $html);
}
2025-12-16 14:34:09 +08:00
2025-12-16 14:59:13 +08:00
// 4. 转换 div → p
$html = preg_replace('/<div[^>]*>/i', '<p>', $html);
$html = preg_replace('/<\/div>/i', '</p>', $html);
2025-12-16 14:34:09 +08:00
2025-12-16 14:59:13 +08:00
// 5. img 只保留 src
$html = preg_replace('/<img[^>]*src="([^"]+)"[^>]*>/i', '<img src="$1">', $html);
2025-12-16 14:34:09 +08:00
2025-12-16 14:59:13 +08:00
// 6. table 清洗
$html = preg_replace('/<table[^>]*>/i', '<table>', $html);
$html = preg_replace('/<td[^>]*>/i', '<td>', $html);
$html = preg_replace('/<th[^>]*>/i', '<th>', $html);
2025-12-16 14:34:09 +08:00
2025-12-16 14:59:13 +08:00
// 7. 去除多余空白
$html = preg_replace('/\s+/u', ' ', $html);
$html = str_replace(['<p></p>', '<p> </p>'], '', $html);
return trim($html);
2025-12-16 15:57:44 +08:00
}*/
2025-12-16 14:34:09 +08:00
2025-12-16 10:16:25 +08:00
/**
* docx 转 HTML(自动上传图片到 OSS)
*
* @param string $docxPath docx 文件绝对路径
* @return string HTML
*/
2025-12-16 14:34:09 +08:00
/*function docxToHtmlWithImages(string $docxPath): string
2025-12-16 10:16:25 +08:00
{
if (!is_file($docxPath)) {
return '';
}
// 1. 读取 docx
$phpWord = WordIOFactory::load($docxPath);
// 2. 输出 HTML 到临时文件
$tmpHtml = runtime_path('tmp/' . uniqid() . '.html');
if (!is_dir(dirname($tmpHtml))) {
mkdir(dirname($tmpHtml), 0755, true);
}
$writer = WordIOFactory::createWriter($phpWord, 'HTML');
$writer->save($tmpHtml);
$html = file_get_contents($tmpHtml);
$uploadService = new UploadService();
// 3. 处理 HTML 中的图片
$html = preg_replace_callback(
'/<img[^>]+src="([^"]+)"[^>]*>/i',
function ($matches) use ($tmpHtml,$uploadService) {
$src = $matches[1];
// docx 导出的图片一般是相对路径
if (!str_starts_with($src, 'http')) {
$localImg = dirname($tmpHtml) . '/' . $src;
if (is_file($localImg)) {
// 上传到 OSS
$ossUrl = $uploadService->uploadLocalFile(['path' => $localImg, 'scene' => 'desc']);
return str_replace($src, $ossUrl, $matches[0]);
}
}
return $matches[0];
},
$html
);
// 清理临时文件
@unlink($tmpHtml);
return $html;
2025-12-16 14:34:09 +08:00
}*/
2025-12-16 10:16:25 +08:00
2025-12-13 16:35:34 +08:00
private function extractImages($sheet): array
{
$images = [];
2025-12-15 14:07:07 +08:00
$uploadService = new UploadService();
2025-12-13 16:35:34 +08:00
foreach ($sheet->getDrawingCollection() as $drawing) {
if ($drawing instanceof Drawing) {
2025-12-15 14:07:07 +08:00
// 取行号
2025-12-13 16:35:34 +08:00
preg_match('/\d+/', $drawing->getCoordinates(), $m);
$row = (int)$m[0];
2025-12-15 14:07:07 +08:00
// Excel 临时图片路径
$tmpPath = $drawing->getPath();
if (!is_file($tmpPath)) {
continue;
}
2025-12-13 16:35:34 +08:00
2025-12-15 14:07:07 +08:00
// 上传到 OSS
$ossUrl = $uploadService->uploadLocalFile(['path' => $tmpPath, 'scene' => 'sku']);
2025-12-13 16:35:34 +08:00
2025-12-15 14:07:07 +08:00
// 一行只保留一张主图
$images[$row] = $ossUrl['file_url'];
2025-12-13 16:35:34 +08:00
}
}
2025-12-15 14:07:07 +08:00
2025-12-13 16:35:34 +08:00
return $images;
}
/**
* 下载 Excel 示例模板
*/
public function template(Request $request): Response
{
2025-12-16 17:05:08 +08:00
$filePath = runtime_path() . '/upload/import.zip';
2025-12-13 16:35:34 +08:00
if (!file_exists($filePath)) {
return response('文件不存在', 404);
}
return response()->download(
$filePath,
2025-12-16 17:05:08 +08:00
'导入示例.zip' // 下载时显示的文件名
2025-12-13 16:35:34 +08:00
);
}
2025-12-08 17:37:34 +08:00
}