Laravel 如何处理文件上传:无法保存图像文件名

Laravel How to handle file upload: Can't save image filename

所以我想上传一张图片,但它只正确存储了它的描述。该文件存储为“noimage.jpg”,这意味着文件名未被读取。我正在使用模式顺便说一句。我的数据库名为 galleries 并且迁移包含这些:

控制器:

public function store(Request $request)
    {
        $galleries=new Gallery;
        // Handle File Upload
        if($request->hasFile('upload')){
            // Get filename with the extension
            $filenameWithExt = $request->file('upload')->getClientOriginalName();
            // Get just filename
            $filename = pathinfo($filenameWithExt, PATHINFO_FILENAME);
            // Get just ext
            $extension = $request->file('upload')->getClientOriginalExtension();
            // Filename to store
            $fileNameToStore= $filename.$extension;
            // Upload Image
            $path = $request->upload('upload')->storeAs('public/upload', $fileNameToStore);
        
        // make thumbnails
            $thumbStore = 'thumb.'.$filename.'_'.time().'.'.$extension;
            $thumb = Image::make($request->file('upload')->getRealPath());
            $thumb->save('storage/upload/'.$thumbStore);        
        } else {
            $fileNameToStore = 'noimage.jpg';
        }

        $galleries->description = $request->input('description');
        $galleries->upload = $fileNameToStore;
        $galleries->save();
        
    }

表格:

<form id="uploadForm">
                <div class="modal-body">
                    <input type="hidden" name="id" id="id">                       
                    
                    <!-- Upload image input-->
                    <div class="input-group mb-3 px-2 py-2 rounded-pill bg-secondary shadow-sm">
                        <input  type="file" name="upload" id="upload" onchange="readURL(this);" class="form-control border-0">
                        
                        <label id="upload-label" for="upload" class="font-weight-light text-muted">Choose file</label>

                        <div class="input-group-append">
                            <label for="upload" class="btn btn-light m-0 rounded-pill px-4"> <i class="fa fa-cloud-upload mr-2 text-muted"></i><small class="text-uppercase font-weight-bold text-muted">Choose file</small></label>
                        </div>
                    </div>

                    <!-- Uploaded image area-->
                    <p class="font-italic text-white text-center">The image uploaded will be rendered inside the box below.</p>
                    <div class="image-area mt-4 bg-white"><img id="imageResult" src="#" alt="" class="img-fluid rounded shadow-sm mx-auto d-block"></div>
                    <label>Caption</label>
                    <input type="textarea" class="form-control text-white" name="description" id="description">

                </div>
</form>

AJAX

<script>
$(document).ready(function(){   
    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });
//ADD PICTURE
    $('#btnUpload').click(function(){
        $('#uploadModal').modal('show');
    });

    $('#btnSave').click(function(){
        $.ajax({
            data: $('#uploadForm').serialize(),
            url: "{{ route('home.store') }}",
            type: "POST",
            dataType: 'json', 

            success: function(data){
                $('#uploadModal').modal('hide');
            },

            error: function(data){
                console.log('Error:', data);
            }
        });
    });
//Image reader to show pic when selected
    function readURL(input) {
        if (input.files && input.files[0]) {
            var reader = new FileReader();

            reader.onload = function (e) {
                $('#imageResult')
                    .attr('src', e.target.result);
            };
            reader.readAsDataURL(input.files[0]);
        }
    }

    $(function () {
        $('#upload').on('change', function () {
            readURL(input);
        });
    });

    var input = document.getElementById( 'upload' );
    var infoArea = document.getElementById( 'upload-label' );

    input.addEventListener( 'change', showFileName );
    function showFileName( event ) {
    var input = event.srcElement;
    var fileName = input.files[0].name;
    infoArea.textContent = 'File name: ' + fileName;
    }
});
</script>

您没有在表单标签中添加 "enctype"

更改您的代码:

<form id="uploadForm">

:

<form id="uploadForm" enctype='multipart/form-data'>

如果上述方法不起作用,则:

1.install 这个包通过以下命令:

composer require "laravelcollective/html":"^5.2.0"

2.In config/app 添加这一行:

'providers' => [
      // ...
     **Collective\Html\HtmlServiceProvider::class,**
    // ...
 ],
 
and

'aliases' => [
   // ...
  **'Form' => Collective\Html\FormFacade::class,
  'Html' => Collective\Html\HtmlFacade::class,**
   // ...
],

3.Change 形式:

{!! Form::open([ 'action'=> 'NameofController@store', 'method' => 'POST','enctype' => 'multipart/form-data' ]) !!}
                 <div class="form-group"> 
                    {{Form::text('name','' , ['class' =>'form-control'])}}
                </div>    
                <div class="form-group">    
                    {{Form::text('phone','' , ['class' =>'form-control', 'placeholder' => 'phone' ])}}
                 </div>   
                 <div class="form-group">
                    {{Form::file('image_name')}}
                 </div>
                 {{Form::submit('Submit' , ['class' =>'btn btn-primary' ])}}
{!! Form::close() !!}

您可以通过这种方式使用自定义名称存储您的文件:

$path = $request->file('upload')->store('public/upload/' .$fileNameToStore);

假设您使用 ajax 上传文件,您将需要使用 FormData 对象而不是 .serialize()

    $.ajax({
        data: new FormData($('#uploadForm').get(0)),  // use formdata object
        url: "{{ route('home.store') }}",
        type: "POST",
        dataType: 'json', 
        contentType: false,  // required for
        processData: false,  // jquery ajax file upload
        success: function(data){
            $('#uploadModal').modal('hide');
        },

        error: function(data){
            console.log('Error:', data);
        }
    });