laravel 上传图片API imgur

5us2dqdw  于 2023-10-22  发布在  其他
关注(0)|答案(2)|浏览(111)

我试图使用imgur API来上传我的个人博客封面图片,但我只是得到一个又一个错误,我想我做错了。我正在使用Laravel与Livewire 3,下面我将显示我的代码,我需要帮助将其上传到我的Web服务器。

namespace App\Livewire\Articles;

use GuzzleHttp\Client;
use App\Models\Article;
use Livewire\Component;
use Illuminate\Support\Str;
use Illuminate\Http\Request;
use Livewire\WithFileUploads;
use Illuminate\Validation\Rule;
use Illuminate\Support\Facades\Auth;

class ArticleForm extends Component
{
    use WithFileUploads;

    public Article $article;
    public $img;

    protected function rules() 
    {
        return [
            // 'file' => 'nullable|mimes:jpg,bmp,png',
            // 'image' => 'nullable|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
            'article.title' => 'required|min:3',
            'article.slug'  => [
               'alpha_dash', 
                Rule::unique('articles', 'slug')->ignore($this->article),
            ], 
            'article.body'  => 'required|min:7|max:65,535',
        ];
    }

    public function updated($property)
    {
        $this->validateOnly($property);
    }
    
    public function updatedArticleTitle($title)
    {
        $this->article->slug = Str::slug($title);
    }

    public function mount(Article $article)
    {
        $this->article = $article;
        
    }

    public function register()
    {
        $this->validate();
        $client = new Client;
        $response = $client->img(
            'POST',
            'https://api.imgur.com/3/image', [
            'headers' => [
                'Authorization' => 'Client-ID ' . config('services.imgur.client_id'),
            ],
            'form_params' => [
                'img' => base64_encode(file_get_contents($img->path())),
                'type' => 'base64',
            ],
        ]);

        $responseBody = json_decode($response->getBody(), true);

        if ($responseBody['success']) {
            return response()->json([
                'message' => 'Image uploaded successfully',
                'url' => $responseBody['data']['link'],
            ]);
        } else {
            return response()->json([
                'message' => 'Failed to upload image',
            ], 400);
        }
                
        Auth::user()->articles()->save($this->article);

        session()->flash('msg', __('Article saved'));

        return to_route('article.index');
    }

    public function render()
    {
        return view('livewire.articles.article-form');
    }
}

在我看来,

<form wire:submit="register" enctype="multipart/form-data">
<div class="bg-black mb-3 p-5 flex w-full justify-center items-center border border-dashed h-52">
    <label for="img" class="cursor-pointer">
        Sube la imagen [ jpg, png, svg o gif ]
    </label>
    <input type="file" wire:model="img" id="img" class="hidden">
</div>
<div>
    <x-input-label for="title" :value="__('Title') " class=" text-xl text-amber-300 italic "/>
    <x-text-input id="title" wire:model="article.title" class="block mt-3 mb-4 w-full !bg-transparent border-0 text-xl italic border-b-2 rounded-none placeholder:text-white placeholder:text-xl focus:ring-0 focus:border-[#48ee06]  border-[#39c9d3]" type="text" placeholder="Escribe el título"  :value="old('article.title')" autocomplete="title" />
    <x-input-error :messages="$errors->get('article.title')" class="mt-2 text-xl italic" />
</div>
<div class="  ">
    <x-input-label for="body" :value="__('Content') " class=" text-xl text-amber-300 italic mt-3 mb-3"/>
    <x-panel.textarea placeholder="Escribe el contenido" wire:model="article.body" id="body"></x-panel.area>
    <x-input-error :messages="$errors->get('article.body')" class="mt-2 mb-4 text-xl italic" />
</div>
<x-primary-button class="!normal-case italic !text-[1.24rem] rounded-none w-full !p-4 shadow shadow-stone-950">
    {{ __('Article saved') }}
</x-primary-button>
</form>

未定义变量$img

dgtucam1

dgtucam11#

你有没有试过先用这条线存储图像

$imagePath = $this->img->store('images', 'public');

//First Parameter ('images') defines a folder path where image are stored
//Second Parameter ('public') defines what storage you'll be using to save the image

以下是完整的文档https://laravel.com/docs/10.x/requests
创建$imagePath后,您可以将其放在通过路径调用存储文件的行中

base64_encode(file_get_contents($imagePath))

希望这有用

wlwcrazw

wlwcrazw2#

在ArticleForm类内部,精确地在register函数上。你应该使用$this来获取img公共变量。

$response = $client->img(
            'POST',
            'https://api.imgur.com/3/image', [
            'headers' => [
                'Authorization' => 'Client-ID ' . config('services.imgur.client_id'),
            ],
            'form_params' => [
                'img' => base64_encode(file_get_contents($this->img->path())),
                                                         // ^^^^^^^^^^^^^^^^ This is for calling img public variable
                'type' => 'base64',
            ],
        ]);

相关问题