I.K.Picture & IT Info.

[Spring boot] Upload Progress bar 만들기 본문

Development/Java/Android

[Spring boot] Upload Progress bar 만들기

helpful-intruder 2021. 8. 22. 12:51
반응형

Spring boot를 기반으로 파일을 업로드하고 이를 클라이언트에서 %를 확인할 수 있는 사용자 인터페이스를 구성하는 

방법을 정리합니다. 

 

UI 의 경우에는 부트스트랩을 사용하였고 자바스크립트 편의 사용 때문에 jQuery도 사용하였습니다.

일단, application.properties 에 (application.yaml) 업로드 파일에 대해 설정을 해줘야합니다. 

 

YAML  

servlet:

    multipart:
      max-file-size: 200MB 
      max-request-size: 200MB



Properties

spring.servlet.multipart.enabled=true
spring.servlet.multipart.max-file-size=-1
spring.servlet.multipart.max-request-size=-1
multipart.maxFileSize=-1
multipart.maxRequestSize=-1

 

파일 업로드에 대한 간단한 사용자 인터페이스는 아래 처럼 하시면됩니다.

 

body 아래 있는 자바스크립트가 업로드시 수행되는 처리 프로세스 이고 

ajax 내용을 잘 확인하시면 될 것 같습니다. 

<!DOCTYPE html>

<head>
<link rel="stylesheet" href="/static/css/style.css">

<script src="https://code.jquery.com/jquery-3.4.1.min.js crossorigin="anonymous"></script>

<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" crossorigin="anonymous">

<link  rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" crossorigin="anonymous">

<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" crossorigin="anonymous">


</head>
<body>
<div class="container">
<div class="row">
<div class="col-10 mx-auto">
<form class="mt-5" method="post" enctype="multipart/form-data">
<div class="input-group">
    <div class="custom-file">
        <input type="file" class="custom-file-input" id="customFile" name="file">
        <label class="custom-file-label" for="customFile" data-browse="Select the file">Click to select...</label>
    </div>
    <div class="input-group-append">
        <button type="button" class="btn btn-outline-secondary reset">Re-election</button>
    </div>
</div>
<div class="row mt-3">
<div class="col-12">
<div class="text-center">
<button type="submit" id="uploadFileBtn" class="btn btn-outline-secondary">submit</button>
</div>
</div>
</div>
</form>

   
<div class="progress mt-3">

      <div id="progressBar" class="progress-bar progress-bar-success" role="progressbar"
        aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="width: 0%">0%</div>
    </div>

    <div id="alertDiv" class="mt-3 alert alert-warning alert-dismissible fade" role="alert">
      <font id="alertMsg"></font>
  <button type="button" class="close" data-dismiss="alert" aria-label="Close">
    <span aria-hidden="true">&times;</span>
  </button>
</div>
    
</div>
</div>
</div>

<!-- Import upload.js -->
<script src="/static/js/upload.js"></script>
</body>


<script>


//파일 input 입력에 따른 활성 유무
$('.custom-file-input').on('change',function(){
    $(this).next('.custom-file-label').html($(this)[0].files[0].name); 
    $('button[type=submit]').prop('disabled',false);
}); 

// 업로드 준비 파일 삭제 
$('.reset').click(function(){
    $(this).parent().prev().children('.custom-file-label').html('Click to select...');
    $('.custom-file-input').val(''); 
    $('button[type=submit]').prop('disabled',false);
});


// 업로드 수행
$("#uploadFileBtn").click(function(e){

   e.preventDefault(); 
    $(this).prop('disabled',true);
     
    var file = $('#customFile')[0].files[0];
    var formData = new FormData();
    formData.append("file",file);
    
$.ajax({
      url : '/fileUpload',
      type : 'POST',
      data : formData,
      cache : false,
      contentType : false,
      processData : false,
      xhr: function(){
        var xhr = $.ajaxSettings.xhr() ;
       
        // Set the onprogress event controller 
        xhr.upload.onprogress = function(event){
          var perc = Math.round((event.loaded / event.total) * 100);
          $('#progressBar').text(perc + '%');
          $('#progressBar').css('width',perc + '%');
        };
        return xhr ;
    },
    beforeSend: function( xhr ) { 
          $('#alertMsg').text('');
          $('#progressBar').text('');
          $('#progressBar').css('width','0%');
     }
}).done(function(msg){ 
     $('#alertDiv').addClass("show"); 
     $('#alertMsg').text(msg); 
     $('input[type=file]').val(''); 
     $('button[type=submit]').prop('disabled',false);
}).fail(function(jqXHR){ 
     $('#alertDiv').addClass("show"); 
     $('#alertMsg').text("An error occurred");
});

return false;


});



</script>
</html>
 

 

예제이기 때문에 간단하게 controller에 모든 기능을 넣어보도록 하겠습니다. 

  @PostMapping("/fileUpload")
    public ResponseEntity<?> uploadFile(HttpServletRequest request, @RequestParam("file") MultipartFile[] files)
            throws Exception {


          if (!file.getOriginalFilename().isEmpty()) {
        BufferedOutputStream outputStream = new BufferedOutputStream(
              new FileOutputStream( 
                    new File(“D:/upload”, file.getOriginalFilename())));
        outputStream.write(file.getBytes());
        outputStream.flush();
        outputStream.close();
      }else{
        return new ResponseEntity<>("Empty file or illegal file.",HttpStatus.BAD_REQUEST);
      }
      return new ResponseEntity("File upload successfully",HttpStatus.OK);
    }

 

반응형
Comments