如何在laravel中上传多个图像,并进行适当的验证和文件名错误

yftpprvb  于 2023-06-30  发布在  其他
关注(0)|答案(2)|浏览(140)

我想在Laravel中上传多个图像,错误显示文件名到刀片文件中。比如我想上传四个文件。其中两个是图像,另外两个是PDF文件,所以它应该阻止我这样做,因为我想只是图像上传,也会告诉我这两个PDF文件的名称是不允许的。但我得到了:

The uploads.0 must be an image.
The uploads.0 must be a file of type: jpeg, png, jpg, gif, svg.

The uploads.2 must be an image.
The uploads.2 must be a file of type: jpeg, png, jpg, gif, svg.

因此,我希望用户必须知道,到哪个文件,他们犯了错误,因为有可能上传超过20个文件,所以如果我可以打印文件名,他们可以很容易地确定哪里是问题。此外,我不能得到这个错误被打印下来的输入;我在Blade文件中使用此代码时出现此错误,

@if (count($errors) > 0)
<div class="alert alert-danger">
<ul>

  @foreach ($errors->all() as $error)
     <li>{{ $error }}</li>
  @endforeach
</ul>
</div>
@endif

因此,我希望验证应该与文件名,它应该显示在输入文件下面,因为到我的其他输入字段显示。
到我的其他输入字段我已经显示了错误与此为所有错误

@if($errors->has('shipping_code'))
<div class="error text-danger fs-6 fw-400">{{ $errors->first('shipping_code') }}</div>
@endif

进入我的控制器

public function store(Request $request) {

    $validator = Validator::make($request->all(),[

        'shipping_code' => 'required|string',
        'customer_name' => 'required|exists:users,id',
        'shipper_name' => 'nullable|exists:users,id',
        'shipping_details' => 'nullable|string',
        'pickup_date' => 'required|date',
        'delivery_date' => 'nullable|date',
        'driver_name' => 'required|exists:users,id',
        'driver_fee' => 'required|regex:/^\d+(\.\d{1,2})?$/',
        'transaction_fee' => 'required|regex:/^\d+(\.\d{1,2})?$/',
        'remarks' => 'nullable|string',
        'status' => 'required|in:0,1,2,3',
        'uploads' => 'required',
        'uploads.*' => 'image|mimes:jpeg,png,jpg,gif,svg|max:2048'
    ]);

    if ($validator->fails()) {

        return redirect()->route('shipping.create')
                    ->withErrors($validator)
                    ->withInput();
    }
    else{

        DB::transaction(function () use($request) {

            $exPd = explode(',',$request->driver_name);
            $driver_id = $exPd[0];

            $shipping = new Shipping();
            $shipping->shipping_code = $request->shipping_code;
            $shipping->customer_id = $request->customer_name;
            $shipping->shipper_id = $request->shipper_name;
            $shipping->driver_id = $driver_id;
            $shipping->shipping_details = $request->shipping_details;
            $shipping->pickup_date = convertDateToDB($request->pickup_date);
            $shipping->delivery_date = convertDateToDB($request->delivery_date);
            $shipping->driver_fee = $request->driver_fee;
            $shipping->transaction_amount = $request->transaction_fee;
            $shipping->remarks = $request->remarks;
            $shipping->status = $request->status;
            $shipping->created_at = date('Y-m-d H:i:s');
            $shipping->created_by = Auth::user()->id;

            $shipping->save();

            if($request->hasfile('uploads')) {
                foreach($request->file('uploads') as $file)
                {
                    $input['imagename'] = time().'.'.$file->extension();
                    $filePath = public_path('/uploads/shipping_transaction_images/');
                    $img = Image::make($file->path());
                    $img->resize(110, 110, function ($const) {
                        $const->aspectRatio();
                    })->save($filePath.$input['imagename']);
                    $imgData[] = $input['imagename'];
                    $fileModal = new ShippingImage();
                    $fileModal->shipping_id = $shipping->id;
                    $fileModal->image_type = 'pickup';
                    $fileModal->image_file = $input['imagename'];
                    $fileModal->save();
                }
            }
        });

        return redirect()->route('shippings.index')
                            ->with('success','Shipping Transaction Created Successfully');
    }
}
mwg9r5ms

mwg9r5ms1#

你可以这样做你的验证:

$messages = [];
if($request->hasfile('uploads')){
    // dd($request->file('uploads'));
    foreach ($request->file('uploads') as $key => $file) {
        $messages['uploads.'.$key.'.image'] = 'The ' .  $file->getClientOriginalName() . ' must be an image.';
       $messages['uploads.' . $key . '.mimes'] = 'The ' . $file->getClientOriginalName() . ' must be a file of type: :values.';
    }

}
$request->validate([   
    'shipping_code' => 'required|string',
    'customer_name' => 'required|exists:users,id',
    'shipper_name' => 'nullable|exists:users,id',
    'shipping_details' => 'nullable|string',
    'pickup_date' => 'required|date',
    'delivery_date' => 'nullable|date',
    'driver_name' => 'required|exists:users,id',
    'driver_fee' => 'required|regex:/^\d+(\.\d{1,2})?$/',
    'transaction_fee' => 'required|regex:/^\d+(\.\d{1,2})?$/',
    'remarks' => 'nullable|string',
     'status' => 'required|in:0,1,2,3',
    'uploads' => 'required|array',
    'uploads.*' => 'image|mimes:jpg,jpeg,png'
], $messages);

您可以获取其他字段的错误,如您使用的方式:

@if($errors->has('shipping_code'))
<div class="error text-danger fs-6 fw-400">{{ $errors->first('shipping_code') }}</div>
@endif

但是对于上传,您可以使用。
如果未选择文件,则用于获取:

@if ($errors->has('uploads'))
    <div class="help-block has-error">
        <strong>{{ $errors->first('uploads') }}</strong>
    </div>
@endif

如果多个选定的文件有错误:

@if($errors->has('uploads.*'))

    @foreach ($errors->get('uploads.*') as $message)
        @foreach ( $message as $value)
            <div class="help-block has-error">{{ $value }}</div>
        @endforeach
    @endforeach
@endif

它也不会伤害你的DB::transaction。参见 * 获取laravel中失败的多个上传文件的文件名 *。

0qx6xfy6

0qx6xfy62#

<!doctype html>
<html lang="{{ app()->getLocale() }}">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Laravel Uploading</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
<!-- Fonts -->
<link href="https://fonts.googleapis.com/css?family=Raleway:100,600" rel="stylesheet" type="text/css">
<!-- Styles -->
<style>
.container {
margin-top:2%;
}
</style>
</head>
<body>
@if (count($errors) > 0)
<div class="alert alert-danger">
<ul>
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
</div>
@endif
<div class="container">
<div class="row">
<div class="col-md-2"> <img src="/32114.svg" width="80" /></div>
<div class="col-md-8"><h2>Laravel Multiple File Uploading With Bootstrap Form</h2>
</div>
</div>
<br>
<div class="row">
<div class="col-md-3"></div>
<div class="col-md-6">
<form action="/multiuploads" method="post" enctype="multipart/form-data">
{{ csrf_field() }}
<div class="form-group">
<label for="Product Name">Product Name</label>
<input type="text" name="name" class="form-control"  placeholder="Product Name" >
</div>
<label for="Product Name">Product photos (can attach more than one):</label>
<br />
<input type="file" class="form-control" name="photos[]" multiple />
<br /><br />
<input type="submit" class="btn btn-primary" value="Upload" />
</form>
</div>
</div>
</div>
</body>
</html>

// controller code
<?php
namespace App\Http\Controllers;
use App\Item;
use App\ItemDetail;
use Illuminate\Http\Request;
class UploadController extends Controller
{
public function uploadForm()
{
return view('upload_form');
}
public function uploadSubmit(Request $request)
{
$this->validate($request, [
'name' => 'required',
'photos'=>'required',
]);
if($request->hasFile('photos'))
{
$allowedfileExtension=['pdf','jpg','png','docx'];
$files = $request->file('photos');
foreach($files as $file){
$filename = $file->getClientOriginalName();
$extension = $file->getClientOriginalExtension();
$check=in_array($extension,$allowedfileExtension);
//dd($check);
if($check)
{
$items= Item::create($request->all());
foreach ($request->photos as $photo) {
$filename = $photo->store('photos');
ItemDetail::create([
'item_id' => $items->id,
'filename' => $filename
]);
}
echo "Upload Successfully";
}
else
{
echo '<div class="alert alert-warning"><strong>Warning!</strong> Sorry Only Upload png , jpg , doc</div>';
}
}
}
}
}?>

//file storing code
return [
'default' => 'local',
'disks' => [
'local' => [
'driver' => 'local',
'root' => storage_path('app'),
],

相关问题