laravel框架——上傳、下載文件


文件上傳

在config文件夾下新建一個 項目名.php 

return [
    'title' => 'My Test',
    'posts_per_page' => 5,
    'uploads' => [
        'storage' => 'local',
        'webpath' => '/uploads', //上傳文件存放的目錄 在public文件夾下
    ],
];

 

view視圖代碼

{{--如果要上傳文件,必須要在Form里面設置files為true--}}
{!! Form::open(array('url'=>'create/show','files'=>true)) !!}
    {{--name為iamge--}}
    {!! Form::file('image') !!}
    <br />
    {!! Form::submit('提交') !!}
{!! Form::close() !!}
 
        

 

<?php

namespace App\Http\Controllers;
//必須使用這個Request
use Illuminate\Http\Request;
use App\Http\Requests;
use Illuminate\Support\Facades\Input;
use App\Test;

class CreateController extends Controller
{
    public function create(){
        return view('create.create');
    }

    public function show(Request $request){
        if ($image = $request->hasFile('image')){
            $file = $request->file('image');
            //判斷文件上傳過程中是否出錯
            if(!$file->isValid()){
                return '文件上傳出錯!';
            }
            //或者文件夾路徑 如果沒有則返回false
            $destPath = realpath(public_path('uploads'));
            /**
             * 檢查一個文件或目錄是否存在
             * @param 文件或文件夾路徑
             * @return
             */
            if(!file_exists($destPath)){
                /**
                 * 試圖創建指定的目錄的路徑名.
                 * @param string $pathname 文件或文件夾所在路徑.
                 * @param int $mode [optional] 默認情況下,默認的模式為0777(rwxrwxrwx)
                 *         讀、寫、運行三項權限可以用數字表示,就是r=4,w=2,x=1
                 *         r(Read,讀取) w(Write,寫入) x(eXecute,執行)
                 * @param bool $recursive [optional] <p>
                 * 允許嵌套目錄中指定的路徑創造。默認為假
                 * @param resource $context [optional] &note.context-support;
                 * @return bool true on success or false on failure.
                 */
                mkdir($destPath,0755,true);
            }
            /**
             * 返回原始文件名.
             * 這是提取請求的文件已經上傳
             * @return string|null 原來的名字
             */
            $filename = $file->getClientOriginalName();
            /**
             * 將文件移動到一個新的位置.
             * @param string $directory 字符串目錄目標文件夾
             * @param string $name      字符串名稱的新文件名
             * @return 返回文件,一個表示新文件的文件對象
             * @throws FileException if, 如果因為任何原因,文件不能被移動
             */
            if(!$file->move($destPath,$filename)){
                 return '保存文件失敗!';
            }
            return '文件上傳成功!';
        }

        return '創建成功';
    }
}

  


下載

 

public function down()
    {
        return response()->download(realpath(base_path('public/uploads')).'/logo.png',
            'Laraveldown.png');
    }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM