我想在我的Laravel/VueJS项目中实现图像上传系统,但我找不到正确的方法。如何设置Controller
函数以处理此上传?
编辑:
这是我的编辑器配置:
config: {
imageUploadParam: 'imageFile',
imageUploadURL: '/froala/upload/image',
imageUploadMethod: 'POST',
imageMaxSize: 5 * 1024 * 1024,
imageAllowedTypes: ['jpeg', 'jpg', 'png'],
}
这是处理请求的函数:
public function uploadImage(Request $request)
{
$file = $request['imageFile'];
$name = $file->getClientOriginalName();
$name = strtolower(str_replace(' ', '', $name));
$path = $file->hashName();
$image = Image::make($file);
Storage::put("/threads/{$path}", (string) $image->encode());
$multimedia = Multimedia::create([
'name' => $name,
'path' => $path
]);
return ['link' => $multimedia->path];
}
我正在使用干预图像库来处理图像上传。
编辑 2:
我收到与csrf
令牌相关的 419 错误。那么,如何将其传递给函数呢?我知道如何获取它,但是使用编辑器的imageUploadParams
配置不起作用:
imageUploadParams: {
csrf: this.csrf
}
csrf: document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
您需要传递正确的 X-CSRF-TOKEN 值以避免 419 错误。
首先检查您是否在元标头中定义了如下所示的令牌:
<meta name="csrf-token" content="{{ csrf_token() }}">
在 VueJS 的早期添加:
var csrf_token = $('meta[name="csrf-token"]').attr('content');
然后将以下内容添加到您的 Froala 配置部分:
config: {
requestHeaders: {
'X-CSRF-TOKEN': csrf_token
},
媒体文件现在应该传递到Laravel中的媒体上传功能。
从文档中:
当图像插入所见即所得的HTML编辑器时,会自动向服务器发出HTTP请求。
可以使用imageUploadURL
配置选项指定将向其发出请求的特定 URL。
设置routes.php
文件以将请求正确定向到所选控制器:
Route::post('/upload', 'FilesController@store');
然后,在控制器中,您可以像往常一样处理图像上传。重要的部分是保存文件后返回文件的路径。
返回的 JSON 需要看起来像:{ "link": "path/to/image.jpg" }
下面是一个示例:
public function store(){
$filepath = request()->file('file')->store('images', 'public');
return ['link' => $filepath];
}
当然,请随意进行您需要的任何类型的验证或处理。
imageUploadParams: {
csrf: this.csrf
}
使用这个
imageUploadParams: {
_token: this.csrf
}
从文档中查看此内容