×ðÁú¿­Ê±¹ÙÍøµÇ¼

laravelÔõÑùʵÏÖ±ÜÃâ±»ÏÂÔØ

ÔÚÐÅϢʱ´ú£¬²»¿É×èÖ¹µØ±£´æÐèÒª¶ÔÊý¾Ý¾ÙÐб£»¤µÄÇéÐΡ£¹ØÓÚwebÓ¦ÓóÌÐò¶øÑÔ£¬ÆäÖÐÒ»Ïî»ù±¾µÄÇå¾²²½·¥¾ÍÊDZÜÃâÓû§»òÕß²»·¨³ÌÐòÏÂÔØÖ¸¶¨µÄÎļþ¡£

ÔÚLaravel¿ò¼ÜÖУ¬ÏëÒª±ÜÃâÎļþ±»ÏÂÔصÄÒªÁì½ÏÁ¿¼òÆÓ¡£±¾ÎĽ«»áÏÈÈݼ¸¸öÍ×ÉƱ£»¤ÎļþµÄÒªÁ죬´Ó¶øʹÍøÕ¾Ô½·¢Çå¾²£¬²¢ÇÒ×èÖ¹±»ºÚ¿Í¹¥»÷¡£

Ò»¡¢Ê¹ÓÃLaravelµÄRoutingÒªÁì

ÔÚLaravelÖУ¬¿ÉÒÔʹÓÃRoutingÀ´¿ØÖÆÄÄЩÎļþ¿ÉÒÔ±»ÏÂÔØ£¬ÄÄЩ²»¿É±»ÏÂÔØ¡£

Step 1 ¨C ½¨ÉèController

ÔÚapp/Http/ControllersĿ¼Ï½¨ÉèÒ»¸öеĿØÖÆÆ÷¡£ÎÒÃÇʹÓÃÒÔÏÂÏÂÁ

php artisan make:controller DownloadController

µÇ¼ºó¸´ÖÆ

Ëü»áÔÚControllersÎļþ¼ÐÖÐÌìÉúÒ»¸öеĿØÖÆÆ÷£º

<?php namespace App\Http\Controllers;

class DownloadController extends Controller
{
    //
}

µÇ¼ºó¸´ÖÆ

Step 2 ¨C ½¨ÉèRoute

ÎÒÃÇ¿ÉÒÔÓÃÒÔÏ·ÓÉŲÓÃDownloadControllerÖеÄÒªÁ죺

Route::post('/download/{file_name}', 'DownloadController@downloadFile')-&gt;name('download.file');

µÇ¼ºó¸´ÖÆ

Step 3 ¨C ½¨ÉèDownloadÒªÁì

ÏÂÒ»²½ÊÇΪDownloadController½¨ÉèÒ»¸öеÄÒªÁ죬ÒÔ±ã¿ÉÒÔ´ÓGET·ÓÉÖÐŲÓøÃÒªÁì¡£

<?php namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Response;

class DownloadController extends Controller
{
    public function downloadFile($fileName)
    {
        $file = Storage::disk('public')->get($fileName);

        return Response::download($file, $fileName);
    }
}

µÇ¼ºó¸´ÖÆ

ÏÖÔÚ£¬¿ÉÒÔÔÚWebä¯ÀÀÆ÷ÖÐÊäÈëÒÔÏÂURLµØµã£¬²âÊԸóÌÐò£º

http://127.0.0.1:8000/download/before-download-test-file.txt

µÇ¼ºó¸´ÖÆ

¶þ¡¢Ê¹ÓÃFileÀàµÄÒªÁì

ÕâÖÖÒªÁìʹÓõÄÊÇPHPµÄfile_get_contents()º¯Êý£¬¸Ãº¯Êý¾ßÓлá¼ûÎļþºÍ¶ÁÈ¡ÆäÄÚÈݵĹ¦Ð§¡£

Route::get('/download', function(){
    $file = public_path()."/test.zip";
    $headers = array(
              'Content-Type: application/octet-stream',
            );
    return Response::download($file, 'test.zip', $headers);
});

µÇ¼ºó¸´ÖÆ

Èý¡¢Ö±½Ó¶ÁÈ¡Îļþ

µÚÈýÖÖÒªÁìÊÇ×î³£¼ûµÄÒ»ÖÖÒªÁ죬Æä»ù±¾Ë¼Ð÷Êǽ«ÎļþÖ±½Ó¶ÁÈëÄÚ´æ²¢·¢Ë͸ø¿Í»§¶Ë¡£

Route::get('/download', function(){
    $file = public_path()."/test.zip";
    $headers = array(
              'Content-Type: application/octet-stream',
            );
    return Response::make(file_get_contents($file), 200, $headers);
});

µÇ¼ºó¸´ÖÆ

С½á

¹ØÓÚÔõÑù±ÜÃâLaravelÖеÄÎļþ±»ÏÂÔØ£¬Óм¸ÖÖ¿Ú¾¶¿ÉÒÔÑ¡Ôñ¡£×î³õ£¬¿ÉÒÔʹÓÃRoutingÀ´¿ØÖÆÄÄЩÎļþ¿ÉÒÔ±»ÏÂÔØ£¬ÄÄЩ²»¿É±»ÏÂÔØ¡£³ý´ËÖ®Í⣬ÉÐÓÐÁ½ÖÖ±ê×¼ÒªÁ죺ʹÓÃLaravelµÄFileÀࣨfile_get_contents()£©»òÖ±½Ó¶ÁÈ¡Îļþ¡£¹ØÓÚÎļþ±£»¤ºÍÏÂÔØÇå¾²£¬°ü¹ÜÍøÕ¾Çå¾²ÖÁ¹ØÖ÷Òª£¬ÈôÊÇ׼ȷʵÑ飬ÕâЩҪÁì¿ÉÒÔÔöÇ¿ÍøÕ¾µÄÇå¾²ÐÔ£¬×èÖ¹±»Ðéα¹¥»÷¡£

ÒÔÉϾÍÊÇlaravelÔõÑùʵÏÖ±ÜÃâ±»ÏÂÔصÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡

ÃâÔð˵Ã÷£ºÒÔÉÏչʾÄÚÈÝȪԴÓÚÏàÖúýÌå¡¢ÆóÒµ»ú¹¹¡¢ÍøÓÑÌṩ»òÍøÂçÍøÂçÕûÀí£¬°æȨÕùÒéÓë±¾Õ¾Î޹أ¬ÎÄÕÂÉæ¼°¿´·¨Óë¿´·¨²»´ú±í×ðÁú¿­Ê±¹ÙÍøµÇ¼ÂËÓÍ»úÍø¹Ù·½Ì¬¶È£¬Çë¶ÁÕß½ö×ö²Î¿¼¡£±¾ÎĽӴýתÔØ£¬×ªÔØÇë˵Ã÷À´ÓÉ¡£ÈôÄúÒÔΪ±¾ÎÄÇÖÕ¼ÁËÄúµÄ°æȨÐÅÏ¢£¬»òÄú·¢Ã÷¸ÃÄÚÈÝÓÐÈκÎÉæ¼°ÓÐÎ¥¹«µÂ¡¢Ã°·¸Ö´·¨µÈÎ¥·¨ÐÅÏ¢£¬ÇëÄúÁ¬Ã¦ÁªÏµ×ðÁú¿­Ê±¹ÙÍøµÇ¼ʵʱÐÞÕý»òɾ³ý¡£

Ïà¹ØÐÂÎÅ

QR code
ÍøÕ¾µØͼ