我最近一直在拿起Laravel并掌握它,我创建了一个简单的网站,允许我制作和编辑文章 - 我现在想要实现的是添加一个图像上传器。
我已经购买了image cropper,它具有响应性,非常适合手机和台式机,但是当我将它添加到我的Laravel项目时,我有点卡住了。
在下载中有一些文件很多是.js
文件和一些PHP文件,我读到我需要在Slim.php
目录中添加App/
文件,我已经完成了我还添加了js文件,包括使上传器出现在视图中。
我遇到困难的时候点击我添加文件并点击上传,它会抛出一个错误并检查网络尝试将数据发送到我尚未添加的articles/async.php
- 我的问题是这在项目中的位置基本上只是一个脚本?我发现的信息并没有告诉我需要把它放在哪里。
我的想法是我只需要将脚本添加到我的商店功能中,找到它寻找脚本的位置并将其重定向到商店,但我的想法是,这不会起作用,因为它处理图像然后一次它上传我发送商店的信息。
如果有人能够提供帮助,就像我说Laravel时有点新手一样,那么任何帮助都会很棒。
答案 0 :(得分:4)
我使用Slim和Laravel 5.4应用程序。在我的例子中,我没有使用ajax来提交图像,它是一个标准的表单帖子。以下是我为使其发挥作用所做的工作:
namespace App\Classes;
use App\Classes\Slim;
对于下一部分,我将在前言中说我将Slim裁剪器设置为仅处理一个图像。因此,我将输入的名称更改为“avatar”。这是我正在使用的HTML:
<div class="slim" data-label="Drop profile photo here" data-size="200, 200" data-ratio="1:1">
@if ( $user->avatar )
<img src="{{ $user->avatar }}" />
@endif
<input type="file" name="avatar" />
</div>
这是我的控制器:
public function avatar($id, Request $request)
{
$user = User::findOrFail($id);
if ( $request->avatar )
{
// Pass Slim's getImages the name of your file input, and since we only care about one image, use Laravel's head() helper to get the first element
$image = head(Slim::getImages('avatar'));
// Grab the ouput data (data modified after Slim has done its thing)
if ( isset($image['output']['data']) )
{
// Original file name
$name = $image['output']['name'];
// Base64 of the image
$data = $image['output']['data'];
// Server path
$path = base_path() . '/public/img/avatars/';
// Save the file to the server
$file = Slim::saveFile($data, $name, $path);
// Get the absolute web path to the image
$imagePath = asset('img/avatars/' . $file['name']);
$user->avatar = $imagePath;
$user->save();
}
}
return redirect()->back()->with('success', "User's profile picture has been updated!");
}
我希望这会有所帮助
答案 1 :(得分:1)
比Slim类更好的方法是允许在本地上载或在Amazon S3之类的远程服务器上进行选择。
public function upload(Request $request)
{
if ($request->hasFile('slim_output_0'))
{
$image = $request->file('slim_output_0');
if ($image->isValid())
{
$extension = $image->getClientOriginalExtension();
$origFileName = Str::slug($image->getClientOriginalName());
$fileName = Str::slug(Str::replaceFirst($extension, '', $origFileName)).'.jpg';
$path = '....';
/**
* PROCESS UPLOAD WITH LARAVEL
* Permit local upload or Amazon S3 Upload
*/
return response()->json([
'status' => 'success',
'name' => $fileName,
'path' => $path.$fileName
]);
}
}
return response()->json([
'status' => 'failure',
'message' => 'Picture not found'
]);
}