[Javascript] Html태그로 파일 다운로드(base64)를 하는 방법


안녕하세요. 명월입니다.


이 글은 Html태그로 파일 다운로드(base64)를 하는 방법에 대한 글입니다.


우리가 웹 서비스에서 파일을 전송하기 위해서는 http 프로토콜 해더에 「Content-type: application/octet-stream」를 넣어야 합니다.

<?php
  if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // POST의 경우에는
    try{
      if(@$handle = fopen('nowonbuntistory.png', 'r')) {
        $contents = fread($handle, filesize('nowonbuntistory.png'));
      }
    } catch(Exception $e){
      print_r($e);
      die();
    } finally{
      @fclose($handle);
    }
    // 파일을 업로드, 브라우져에서는 다운로드 타입으로 변경한다.
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename=image.png'); 
    header('Content-Length: ' . filesize('nowonbuntistory.png'));
    header("Content-Type:image/png");
    // byte타입으로 body를 작성한다.
    echo $contents;
    // 아래의 body가 읽히지 않도록 중단한다.
    die();
  }
?>
<!DOCTYPE html>
<html>
<head>
  <title>title</title>
  <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
</head>
<body>
file download
<!-- POST Request를 요청한다. -->
<form method="POST">
  <input type="submit">
</form>
</body>
</html>

그러나 서버의 Request가 없이 html태그만으로 다운로드 링크를 만들 수 있습니다. a태그에 href에 base64타입으로 데이터를 넣은 후에 download 속성에 파일 명을 넣으면 파일 다운로드가 가능합니다.

<?php
  try{
    if(@$handle = fopen('nowonbuntistory.png', 'r')) {
      $contents = fread($handle, filesize('nowonbuntistory.png'));
    }
  } catch(Exception $e){
    print_r($e);
    die();
  } finally{
    @fclose($handle);
  }
  // 파일을 읽어서 base64로 인코딩한다.
  $base64data = base64_encode($contents);
?>
<!DOCTYPE html>
<html>
<head>
  <title>title</title>
  <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
</head>
<body>
<!-- 다운로드 파일명은 download 속성에 넣고 href에 data 속성을 입력후에 뒤에 base64타입으로 데이터를 response한다. -->
<a href="data:image/png;base64,<?=$base64data?>" download="linkdownload1.png">file download</a><br />
<a href="data:image/png;base64,<?=$base64data?>" download="linkdownload2.png">file download</a><br />
<a href="data:image/png;base64,<?=$base64data?>" download="linkdownload3.png">file download</a><br />
</body>
</html>


예제

file download

file download

file download

다음은 javascript로 a태그를 작성하는 방법입니다.

<!DOCTYPE html>
<html>
<head>
  <title>title</title>
  <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
</head>
<body>
<input type="file" id="fileupload"><button id="uploadClick">upload</button>
<script>
$('#uploadClick').on('click', function() {
  var file = $("#fileupload")[0].files[0];
  var filename = file.name;
  var reader = new FileReader();
    reader.onload = function(e) {
    var base64data = reader.result;
    //a 태그를 생성한다.
    var link = document.createElement('a');
    // href에 base64데이터를 넣는다.
    link.href = base64data;
    link.download = "linkdownload4.png";
    document.body.appendChild(link);
    // 클릭한다.
    link.click();
    // 다운로드가 되면 태그를 삭제한다.
    document.body.removeChild(link);
  }
  reader.readAsDataURL(file);
});
</script>
</body>
</html>

예제2

여기까지 Html태그로 파일 다운로드(base64)를 하는 방법에 관한 설명이었습니다.


궁금한 점이나 잘못된 점이 있으면 댓글 부탁드립니다.