php laravel 架構 之檔案上傳

來源:互聯網
上載者:User

標籤:

用戶端  

<form method="POST" action="" enctype="muitipart/form-data">  

    <input type="file" name="myfile" />  

    <input type="submit" name="submit" value="Submit" />  

</form>  

提交到伺服器端.  

$file = Input::file(‘myfile‘);  

if($file -> isValid()){  

    //檢驗一下上傳的檔案是否有效.  

         $clientName = $file -> getClientOriginalName();      

    $tmpName = $file ->getFileName();    //    緩衝在tmp檔案夾中的檔案名稱    例如    php8933.tmp 這種類型的.  

   $realPath = $file -> getRealPath();    //這個表示的是緩衝在tmp檔案夾下的檔案的絕對路徑  

        //例如我的是:      G:\xampp\tmp\php5A69.tmp      

       //這裡要注意,如果我使用接下來的move方法之後, getRealPath() 就找不到檔案的路徑了.因為檔案已經被移走了.      

        所以這裡道出了檔案上傳的原理,將檔案上傳的某個臨時目錄中,然後使用Php的函數將檔案移動到指定的檔案夾.      

       $entension = $file -> getClientOriginalExtension(); //上傳檔案的尾碼.      

    $mimeTye = file -> getMimeType();//大家對mimeType應該不陌生了. 我得到的結果是 image/jpeg.  

        //這裡要注意一點,以前我們使用      mime_content_type()      ,在php5.3 之後,開始使用 fileinfo 來擷取檔案的mime類型.所以要加入 php_fileinfo的php拓展.windows下是 php_fileinfo.dll,在php.ini檔案中將 extension=php_fileinfo.dll前面的分號去掉即可.當然要重啟伺服器.      

  最後我們使用  

  $path = $file -> move(‘storage/uploads‘);  

  如果你這樣寫的話,預設是會放置在 我們 public/storage/uploads/php79DB.tmp    

  貌似不是我們希望的,如果我們希望將其放置在app的storage目錄下的uploads目錄中,並且需要改名的話..  

  $path = $file -> move(app_path().‘/storage/uploads‘,$newName);  

  這裡app_path()就是app檔案夾所在的路徑.$newName 可以是你通過某種演算法獲得的檔案的名稱.主要是不能重複產生衝突即可.      比如 $newName = md5(date(‘ymdhis‘).$clientName).".".$extension;  

  利用日期和用戶端檔案名稱結合 使用md5 演算法加密得到結果.不要忘記在後面加上檔案原始的拓展名.  


php laravel 架構 之檔案上傳

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.