【问题标题】:How to show only .pdf file when browse file to upload using Laravel 5.0?使用 Laravel 5.0 浏览要上传的文件时如何仅显示 .pdf 文件?
【发布时间】:2016-10-05 13:13:06
【问题描述】:

我正在使用 Laravel 5.0。我有一个文件上传功能。进行得顺利。但我想让用户只上传 pdf 文件。我想在浏览文件时,存储只显示只有 .pdf 文件的文件。我想对要上传的文件设置大小限制。

这里是风景

    <div class="form-group">
        <label for="upload_file" class="control-label col-sm-2">Upload File</label>
        <div class="col-sm-9">
            <input class="form-control" type="file" name="upload_file" id="upload_file" required>
        </div>  
    </div>

这里是控制器

$destination = 'files';

    if($request->hasFile('upload_file')) {
        $file = $request->file('upload_file');
        $extension = $file->getClientOriginalExtension();
        $file_name =  str_replace('/','_',$request['nomor_surat']) . '-' . $kode_divisi[0]->kode_divisi . '.' . $extension;

        $file->move($destination, $file_name );
    }
    $upload_file = $file_name;

    $surat = new Surat();
    $surat->upload_file = $upload_file;
    $surat->save();

接下来我该怎么做?我应该在我的控制器和路由和视图中添加什么?

【问题讨论】:

    标签: php laravel pdf file-upload laravel-5


    【解决方案1】:

    您可以限制用户仅使用 HTML 文件输入 accept 属性浏览 PDF 文件:

    <input type="file" accept="application/pdf" /> 
    

    要限制大小,可以在服务器端做:

    $file = $request->file('upload_file');
    
    //no files larger than 700kb
    if ($file->getSize() > 700000)
    {
        //respond not validated, file too big.
    }
    

    您也可以在服务器上验证文件类型:

    if ($file->getClientMimeType() !== 'application/pdf')
    {
        //respond not validated, invalid file type.
    }
    

    【讨论】:

    • 无论如何,当我们按下提交按钮时,您知道如何让响应文件变得像警报一样大吗?我正在使用if ($file-&gt;getSize() &gt; 700000) { echo "Sorry, your file is too large."; }
    • 在服务器端做这个检查时,文件会先上传。这有时会浪费带宽。您可以在浏览器上进行检查的另一种方法是使用 javascript,并在提交之前验证文件。看看这个:stackoverflow.com/questions/3717793/…
    猜你喜欢
    • 2019-09-08
    • 2013-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-28
    • 2020-01-28
    • 2020-01-25
    • 2020-11-29
    相关资源
    最近更新 更多