Tag Archive download

Byphunsanit

Fetch API: Download

ที่นี้มาถึงการที่ใช้ fetch download file จาก server ซึ่งวิธีนี้ง่ายกว่าการใช้ jQuery ดึงไฟล์มามาก จากที่เคยเขียน jQuery ajax download file เอาไว้จะเห็นว่าวิธีนี้ง่ายกว่ามาก

เริ่มจากการที่โหลด download.js มาก่อน โดยใช้คำสั่ง npm i downloadjs
ไฟล์กลางที่ไว้ใช้ร่วมกัน

scripts.js

/*
pitt phunsanit
default fetch api options
version 1
*/
let fetchOptions = {
    "headers": {
        'Content-type': 'application/x-www-form-urlencoded; charset=UTF-8'
    },
    "method": "post"
};

/*
pitt phunsanit
get file name from fetch api
version 1
*/
function fetchGetFilename(response) {
    let filename = '';
    let disposition = response.headers.get('Content-Disposition');
    if (disposition && disposition.indexOf('attachment') !== -1) {
        let filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
        let matches = filenameRegex.exec(disposition);
        if (matches != null && matches[1]) {
            filename = matches[1].replace(/['"]/g, '');
        }
    }
    return filename;
}

/*
pitt phunsanit
get status from fetch api
version 1
*/
function fetchStatus(Response) {
    if (Response.status >= 200 && Response.status < 300) {
        return Promise.resolve(Response);
    } else {
        return Promise.reject(new Error(Response.status + ' : ' + Response.statusText));
    }
}

ตัวอย่างการใช้ fetch download file โดยใช้ downloadjs ช่วยให้ทำงานได้ทุกบราวเซอร์ (ยกเว้น IE ถ้าจะใช้กลับไปอ่าน Fetch API)

JavaScript/fetch.download.html
<!DOCTYPE html>
<html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

      <meta name="author" content="Pitt Phunsanit">
      <title>fetch: download</title>
   </head>
   <body>
      <script src="../node_modules/downloadjs/download.min.js"></script>
      <script src="../scripts.js"></script>
      <script>
fetchOptions.body = 'file=ISO 3166-1 two aplha COUNTRY codes (01102009).xls&token=HH89VOiirgXlCdEqDrFs';

fetch('http://localhost/snippets/PHP/download.php', fetchOptions)
    .then(fetchStatus)
    .then(
        function(response) {
            if (response.ok) {
                let fileName = fetchGetFilename(response);
                let mimeType = response.headers.get('Content-Type');

                response.blob().then(function(blob) {
                    download(blob, fileName, mimeType);
                });
            }
        }
    )
    .catch(function(error) {
        alert(error);
    });
      </script>

</body></html>

อ่านเพิ่มเติม

Byphunsanit

php: download ไฟล์จาก server

ตัวอย่าง code php ไว้ download ไฟล์จาก server

PHP/download.php
<?php
$fileDir = '../assets/';
$token = 'HH89VOiirgXlCdEqDrFs';

if ($_REQUEST['token'] != $token) {
    exit('bad token');
}

$file = $fileDir . $_REQUEST['file'];
if (file_exists($file)) {
    header('Content-Description: File Transfer');
    header('Content-Type: ' . mime_content_type($file));
    header('Content-Disposition: attachment; filename="' . basename($file) . '"');
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');
    header('Content-Length: ' . filesize($file));

    //readfile($file);
    echo file_get_contents($file);
} else {
    exit('file not found');
}

เพราะว่า ออกแบบให้สามารถโหลดไฟล์อะไรก็ได้จาก server เลยมีการใช้ token ช่วยในการตรวจสอบความปลอดภัยเล็กน้อย ของจริงต้องแก้ให้ตรวจ token ซับซ้อนกว่านี้เพื่อความปลอดภัย

Byphunsanit

ติดตั้ง Visual Studio offline ไม่ต่อเน็ต

การติดตั้ง Visual Studio แบบไม่ต้องใช้เน็ต ทำได้โดย

  1. ดาวน์โหลดตัวติดตั้งมาจาก https://visualstudio.microsoft.com (ตัวติดตั้งแบบออนไลน์ปกตินั่นละ)
  2. ใช้ command line โหลดไฟล์ติดตั้งทั้งหมดโดย –layout จะระบุตำแหน่งที่เก็บตัวติดตั้งไว้และหวังว่าจะมีที่ให้เก็บข้อมูลพอ (ประมาณ 35 GB เอง)
    ติดตั้งทุกภาษา
    vs_community.exe --layout C:\vs201807
    ติดตั้งภาษาเดียว
    vs_community.exe --layout C:\vs201807 --lang En-us
    ติดตั้งหลายภาษา
    vs_community.exe --layout C:\vs201807 --lang En-us Ja-jp Ko-kr
  3. รอมัน download ไปเรื่อยๆ (เป็นชั่วโมง)
  4. เอา folder ที่ระบุไว้ใน –layout ไปติดตั้ง

ภาษาทั้งหมดที่มี List of language locales

Language-locale
Language
Cs-cz Czech
De-de German
En-us English
Es-es Spanish
Fr-fr French
It-it Italian
Ja-jp Japanese
Ko-kr Korean
Pl-pl Polish
Pt-br Portuguese – Brazil
Ru-ru Russian
Tr-tr Turkish
Zh-cn Chinese – Simplified
Zh-tw Chinese – Traditional

 

อ่านเพิ่มเติม Use command-line parameters to install Visual Studio 2017

Byphunsanit

curl: ดาวน์โหลดไฟล์

การใช้ curl ไป download file จากเซิร์ฟเวอร์อื่นๆ ไม่ได้ซับซ้อนเหมือนการอัพโหลดในตัวอย่าง curl: ส่งไฟล์ การทำงานค่อนข้างตรงไปตรงมาก คือ มีไฟล์ที่มี code curl ทำหน้าที่ request และมีไฟล์หรือโปรแกรมที่ทำหน้าที่จ่ายไฟล์ให้ โดยดัดแปลงให้แสดง error กลับมาในรูปแบบที่ง่ายกับการแสดง error ในฝั่งรีเควสท์

เพื่อความปลอดภัย จะมีการเขียนการตรวจสอบเล็กน้อย

  • จะส่ง token มาและทั้ง 2 ไฟล์จะต้องมีค่าเท่าๆกัน ในความเป็นจริง ควรจะมีการเขียนที่ดีกว่านี้ เช่น เปลี่ยน token ตามช่วงเวลา
  • ไม่ควรให้ร้องขอไฟล์โดยใช้ full path และเพื่อป้องกันการใช้ฝั่งรับในการ download ไฟล์อื่นๆ จึงต้องกำหนดโฟลเดอร์เริ่มต้นไว้ให้ดาวน์โหลดไฟล์ในโฟลเดอร์ที่กำหนดไว้เท่านั้น
  • <?php
    header('Cache-Control: no-cache, no-store, must-revalidate');
    header('Expires: 0');
    header('Pragma: no-cache');
    
    $post = [
        'file' => 'test.docx',
        'token' => $token,
    ];
    $token = 'HH89VOiirgXlCdEqDrFs';
    $url = 'http://localhost/snippets/PHP/download.php';
    
    $ch = curl_init();
    
    curl_setopt_array($ch, [
        CURLOPT_ENCODING => 'UTF-8',
        CURLOPT_FRESH_CONNECT => true,
        CURLOPT_POST => 1,
        CURLOPT_POSTFIELDS => http_build_query($post),
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_URL => $url,
    ]);
    
    $result = curl_exec($ch);
    
    switch ($result) {
        case 'bad token':{
                curl_close($ch);
                exit('check token in ' . $url);
            }break;
    
        case 'file not found':{
                curl_close($ch);
                exit('file not found in target server.');
            }break;
    
        default:{
                header('Content-Disposition: attachment; filename="' . $post['file']);
                echo $result;
            }
    }
    curl_close($ch);

    <?php
    $fileDir = '../assets/';
    $token = 'HH89VOiirgXlCdEqDrFs';
    
    if ($_REQUEST['token'] != $token) {
        exit('bad token');
    }
    
    $file = $fileDir . $_REQUEST['file'];
    if (file_exists($file)) {
        header('Content-Description: File Transfer');
        header('Content-Type: ' . mime_content_type($file));
        header('Content-Disposition: attachment; filename="' . basename($file) . '"');
        header('Expires: 0');
        header('Cache-Control: must-revalidate');
        header('Pragma: public');
        header('Content-Length: ' . filesize($file));
    
        //readfile($file);
        echo file_get_contents($file);
    } else {
        exit('file not found');
    }