You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

53 lines
1.5 KiB
PHP

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

<?php
namespace App\Http\Controllers\API\Admin;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use App\Lib\Rs;
class UploadController extends Controller
{
/**
* 通用图片上传接口
*/
public function uploadImage(Request $request)
{
// 验证请求数据
if (!$request->hasFile('image')) {
return Rs::error('请选择要上传的图片');
}
$file = $request->file('image');
// 验证文件类型
$allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
if (!in_array($file->getMimeType(), $allowedTypes)) {
return Rs::error('只允许上传JPG/PNG/GIF/WEBP格式的图片');
}
// 验证文件大小5MB
$maxSize = 5 * 1024 * 1024;
if ($file->getSize() > $maxSize) {
return Rs::error('图片大小不能超过5MB');
}
// 生成唯一文件名
$filename = 'img_' . date('YmdHis') . '_' . uniqid() . '.' . $file->getClientOriginalExtension();
$path = $file->storeAs('images', $filename, 'public');
if ($path) {
// 返回相对路径和完整URL
$relativePath = 'storage/' . $path;
$fullUrl = asset('storage/' . $path);
return Rs::success([
'url' => $relativePath,
'full_url' => $fullUrl
]);
} else {
return Rs::error('图片上传失败');
}
}
}