簡體   English   中英

laravel - 多次上傳並將不同的文件名保存到數據庫

[英]laravel - multi upload and save different filename to database

我想上傳多個圖像並將不同的文件名保存到數據庫中。

我有一個 HTML 代碼:

<input type="file" id="upload_file" name="image[]" multiple/>

和一個數據庫表:

id 
image1 
image2 
image3 
image4 
image5 
created_at 
updated_at

能不能這樣?

image[]是一個數組。您可以通過這種方式將數組元素存儲在不同的列中:

public function store(Request $request)
{
    $model=new Model();
    $model->image1=$request->image[0];
    $model->image2=$request->image[1];
    $model->image3=$request->image[2];
    ...
    $model->save();
}

正常方式:

$image=$_POST['image'];
INSERT INTO table (image1,image2,image3...)VALUES('$image[0]','$image[1]','$image[2]...);

我相信正確的方法是制作一個帶有相應表格的Image模型,然后您將設置它與其他模型的關系。 就像是:

public function store(Request $request)
{
    $model = new RelatedModel(); // This is a related model example

    $images = $request->file("image.*");
    foreach($images as $uploadedImage)
    {
        $path = $uploadedImage->store('path/images', 'local'); // disk can be null, it will then use the default disk in filesystems.php
        $image = new Image();
        // A way you want to use to give the image a name
        $image->name = $this->generateName(); 
        $image->path = $path;
        // Where relatedModel is the method on Image model defining a belongsTo relation for example with RelatedModel
        $image->relatedModel()->associate($model); 
        $image->save();
    }

}

我不知道您為什么要按照問題中指定的方式保存圖片。 但是如果你堅持,你必須添加新的字段

id | image1 | image1_name | image2 | image2_name ...

然后在你的代碼中:

public function store(Request $request)
{
    $model=new Model();

    // This is a function you would make to generate a different name than the path
    $model->image1_name = $this->generateName(); 
    $model->image1 = $request->file("image.0");->store('path/images', 'local');
    $model->image2_name = $this->generateName(); 
    $model->image2 = $request->file("image.1");->store('path/images', 'local');
    // ...etc.

    $model->save();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM