【问题标题】:Laravel How to handle file upload: Can't save image filenameLaravel如何处理文件上传:无法保存图像文件名
【发布时间】:2021-02-20 17:14:34
【问题描述】:

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

  • $table->id();
  • $table->timestamps();
  • $table->string('upload');
  • $table->longtext('description')->nullable();

控制器:

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='multipart/form-data'&lt;form id="uploadForm" enctype='multipart/form-data&gt;
  • nothing changed 文件名仍保存为“noimage.jpg”
  • 欢迎使用stackoverflow,尝试做dd($request-&gt;hasFile('upload'));并检查你是否正确,或者你可以在问题中显示dd($request);
  • 我在 promise: ƒ ( obj ) 中收到了很长的响应文本:&lt;script&gt; Sfdump = window.Sfdump || (function (doc) { var refStyle = doc.createElement(...
  • 试着看看你在控制器的 $request 中得到了什么

标签: laravel file-upload controller store laravel-7


【解决方案1】:

假设您使用 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);
        }
    });

【讨论】:

    【解决方案2】:

    您不要在表单标签中添加 "enctype"

    更改您的代码

    <form id="uploadForm">
    

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

    【讨论】:

    • nothing changed 文件名仍保存为“noimage.jpg”
    【解决方案3】:

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

    1.通过以下命令安装此软件包:

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

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

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

    3.更改表格:

    {!! 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() !!}
    

    【讨论】:

    • 很抱歉,我们暂时还不能使用这种表单格式,只是经典的php和html样式...呵呵
    • 但是这种方法是安全的。
    • 好吧,我们这位教授想让我们这么难过,不能用它。
    【解决方案4】:

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

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

    【讨论】:

      猜你喜欢
      • 2020-08-30
      • 2021-04-27
      • 2018-02-08
      • 2014-02-15
      • 1970-01-01
      • 1970-01-01
      • 2021-12-23
      • 2019-10-02
      • 1970-01-01
      相关资源
      最近更新 更多