【问题标题】:How to upload images to the AWS s3 bucket from laravel-8 through postman?如何通过邮递员将图像从 laravel-8 上传到 AWS s3 存储桶?
【发布时间】:2021-09-13 03:15:46
【问题描述】:

我对 AWS 非常陌生,我在其中创建了 s3 存储桶并将访问密钥区域传递到我的 .env 文件中并编辑了 conig/filesystems.php 并编写了控制器来发布我的数据,我的数据是它包含的混合类型二进制和普通数据,所以我有点困惑我必须在邮递员中使用哪种内容类型(内容类型=,标题内)。如果我使用的是普通内容类型=应用程序/json,并且在正文部分我使用 raw at那时它正在工作,但图像未上传到 s3 存储桶中,当我使用 content-type=multipart/mixed 时出现以下错误,请帮助我解决此问题以及如何通过邮递员从 laravel 将图像上传到 s3 存储桶

Illuminate\Database\QueryException: SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'image' cannot be null (SQL: insert into `books` (`image`, `price`, `title`, `quantity`, `author`, `description`, `user_id`, `updated_at`, `created_at`) values (?, ?, ?, ?, ?, ?, 1, 2021-07-01 08:09:06, 2021-07-01 08:09:06)) in file C:\Users\VICKY\Desktop\8\laravel-bookstore\vendor\laravel\framework\src\Illuminate\Database\Connection.php on line 692

Books.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Books extends Model
{
    use HasFactory;
    protected $fillable = [
        // 'name',
        'image',
        'price',
        'title',
        'quantity',
        // 'ratings',
        'author' ,
        'description'  
    ];
    protected $hidden = [
        'password',
        'remember_token',
        'updated_at'
    ];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];

    /**
     * Return a key value array, containing any custom claims to be added to the JWT.
     *
     * @return array
     */
    public function getJWTCustomClaims()
    {
        return [];
    }

    /**
     * Get the identifier that will be stored in the subject claim of the JWT.
     *
     * @return mixed
     */
    public function getJWTIdentifier()
    {
        return $this->getKey();
    }
   
    //inverse one to many
   public function user(){
       return $this->belongsTo(User::class);
   }
}

BooksController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Books;
use App\Models\User;
use App\Http\Requests;
use Symfony\Component\HttpFoundation\Response;
use App\Http\Resources\Books as BooksResource;
use App\Http\Middleware\Authenticate;

class BooksController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function DisplayBooks()
    {
        $books=Books::all();
        return User::find($books->user_id=auth()->id())->books; 
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function AddBooks(Request $request)
    {
        $book=new Books();
        //$book->name=$request->input('name');
        $book->image=$request->input('image'); 
if($request->hasfile('image'))
            {
            $file = $request->file('image');
            $imageName=time().$file->getClientOriginalName();
            $filePath = 'images/' . $imageName;
            Storage::disk('s3')->put($filePath, file_get_contents($file));
            }
        $book->price=$request->input('price');
        $book->title=$request->input('title');
        $book->quantity=$request->input('quantity');
       // $book->ratings=$request->input('ratings');
        $book->author=$request->input('author');
        $book->description=$request->input('description');
        $book->user_id = auth()->id();          
        $book->save();
        return new BooksResource($book);
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function ShowBook($id)
    {
        $book=Books::findOrFail($id);
        if($book->user_id==auth()->id())
            return new BooksResource($book);
        else{
            return response()->json([
                'error' => 'UnAuthorized/invalid id'], 401);
            }
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function UpdateBook(Request $request, $id)
    {
        $book=Books::findOrFail($id);
        if($book->user_id==auth()->id()){
            //$book->name=$request->input('name');
            $book->image=$request->input('image'); 
            $book->price=$request->input('price');
            $book->title=$request->input('title');
            $book->quantity=$request->input('quantity');
            //$book->ratings=$request->input('ratings');
            $book->author=$request->input('author');
            $book->description=$request->input('description');
            $book->save();
            return new BooksResource($book);
        }
        else
        {
            return response()->json([
                'error' => ' Book is not available ith id'], 404);
        }
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function DeleteBook($id)
    {
        $book=Books::findOrFail($id);
        if($book->user_id==auth()->id()){
            if($book->delete()){
                return response()->json(['message'=>'Deleted'],201);
            }
        }
        else{
            return response()->json([
                'error' => ' Method Not Allowed/invalid Book id'], 405);
        }
    }
}

config/filesystems.php

<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Default Filesystem Disk
    |--------------------------------------------------------------------------
    |
    | Here you may specify the default filesystem disk that should be used
    | by the framework. The "local" disk, as well as a variety of cloud
    | based disks are available to your application. Just store away!
    |
    */

    'default' => env('FILESYSTEM_DRIVER', 'local'),

    /*
    |--------------------------------------------------------------------------
    | Filesystem Disks
    |--------------------------------------------------------------------------
    |
    | Here you may configure as many filesystem "disks" as you wish, and you
    | may even configure multiple disks of the same driver. Defaults have
    | been setup for each driver as an example of the required options.
    |
    | Supported Drivers: "local", "ftp", "sftp", "s3"
    |
    */

    'disks' => [

        'local' => [
            'driver' => 'local',
            'root' => storage_path('app'),
        ],

        'public' => [
            'driver' => 'local',
            'root' => storage_path('app/public'),
            'url' => env('APP_URL').'/storage',
            'visibility' => 'public',
        ],

        's3' => [
            'driver' => 's3',
            'key' => env('AWS_ACCESS_KEY_ID'),
            'secret' => env('AWS_SECRET_ACCESS_KEY'),
            'region' => env('AWS_DEFAULT_REGION'),
            'bucket' => env('AWS_BUCKET'),
            'url' => env('AWS_URL'),
            'endpoint' => env('AWS_ENDPOINT'),
            'visibility'=>'public',
            'use_path_style_endpoint' => env('AWS_USE_PATH_STYLE_ENDPOINT', false),
        ],

    ],

    /*
    |--------------------------------------------------------------------------
    | Symbolic Links
    |--------------------------------------------------------------------------
    |
    | Here you may configure the symbolic links that will be created when the
    | `storage:link` Artisan command is executed. The array keys should be
    | the locations of the links and the values should be their targets.
    |
    */

    'links' => [
        public_path('storage') => storage_path('app/public'),
    ],

];

migration table

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateBooksTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('books', function (Blueprint $table) {
            $table->increments('id');
            $table->string('image');
            $table->integer('price')->unsigned();
            $table->text('title');
            $table->integer('quantity')->length(2)->unsigned();
           // $table->integer('ratings')->length(2)->unsigned();
            $table->string('author');
            $table->longText('description');
            $table->unsignedBigInteger('user_id');
            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('books');
    }
}

在 Headers 部分 Authorization=Bearer token 和 content-type="multipart/mixed"

【问题讨论】:

  • 可以把书的模型贴在这里吗?
  • 你好@MahmoodHussain,我现在发布书籍模型
  • 将文件作为二进制文件存储在数据库中不是一个好主意,您可以使用本地存储,也可以将密钥存储在 AWS 中。这是关于如何通过laravel在AWS上存储文件的教程blog.devgenius.io/laravel-api-file-upload-to-aws-a8e87319b82e

标签: php amazon-s3 postman laravel-8


【解决方案1】:

为了在 laravel 的数据库中简单地将图像存储为二进制,请参考: How to store and retrieve image contents from the database using Laravel

在 AWS 中存储

composer require league/flysystem-aws-s3-v3

在我们的.ENV 文件中编辑以下内容:

AWS_ACCESS_KEY_ID=Access Key Id
AWS_SECRET_ACCESS_KEY=Secret Access Key
AWS_DEFAULT_REGION=Bucket Region
AWS_BUCKET=Bucket Name

架构将$table-&gt;binary('image'); 更改为$table-&gt;string('image');

控制器

if($request->hasfile('image'))
{
    $file = $request->file('image');
    $imageName=time().$file->getClientOriginalName();
    $filePath = 'images/' . $imageName;
    Storage::disk('s3')->put($filePath, file_get_contents($file));
    // After Image is uploaded make entry to database
}

【讨论】:

  • 你好@MahmoodHussain,我想从邮递员上传我的图片,而不是在 s3 存储桶中手动上传
  • 我刚刚提到了这些步骤,并认为您将能够编写代码。当然,您可以通过邮递员或任何其他方法(如前端)来完成
  • 查看更新的答案并添加合并代码 sn-ps 与您的代码,它应该去去
  • 你好@Mahmood Hussain,我根据你的建议更新了代码,但它得到了同样的错误
  • @Sravani 您没有将图像名称保存到数据库中,只需添加 $book-&gt;name=$imageName; 并删除 $book-&gt;image=$request-&gt;input('image');
猜你喜欢
  • 1970-01-01
  • 2017-12-23
  • 2018-03-11
  • 2019-07-09
  • 2020-12-30
  • 1970-01-01
  • 1970-01-01
  • 2021-02-07
  • 2013-10-03
相关资源
最近更新 更多