티스토리 뷰

SW개발/Spring Framework

파일 업로드 구현

개소왕 2020. 4. 20. 16:16

* 클라이언트 
- js - javascript 호출 
jquery.form.js

jquery.MultiFile.js


- js - MultiFile 선언

// 참고 : 사이트에 나온 max_size 가 아니라 maxsize 임

// 파일 추가시 추가되는 html 요소에 대한 수정은 js 파일의 addToList 부분 수정을 통해 가능하다

// input type=file 에 multi 속성을 추가하면 파일 선택창에서 ctrl+클릭을 통해 여러 파일 선택 가능하다

// 하지만 파일 목록에서는 개별로 분리되서 표시되지 않는다

 

$('#myFiles').MultiFile({
//     accept: 'jpg|png|gif', 
max: 1,
maxsize : 600000, // 최대 용량 600mb, 수정하려면 스프링 설정도 바꿔야 함.
    STRING: { //Multi-lingual support : 메시지 수정 가능
        remove : "삭제", //추가한 파일 제거 문구, 이미태그를 사용하면 이미지사용가능
        duplicate : "$file 은 이미 선택된 파일입니다.", 
        denied : "$ext 는(은) 업로드 할수 없는 파일확장자입니다.",
        selected:'$file 을 선택했습니다.', 
        toomuch: "업로드할 수 있는 최대크기를 초과하였습니다.($size)", 
        toomany: "업로드할 수 있는 최대 갯수는 $max개 입니다.",
        toobig: "$file 은 크기가 매우 큽니다. (max $size)"
    },
list:"#uploadListTbl tbody",
//     onFileRemove: function(element, value, master_element) {
//       $('#afile3-list').append('

  • onFileRemove - ' + value + '

')
//     },
//     afterFileRemove: function(element, value, master_element) {
//       $('#afile3-list').append('

  • afterFileRemove - ' + value + '

')
//     },
//     onFileAppend: function(element, value, master_element) {
//      console.log(element);
//      console.log(master_element);
//     },
//     afterFileAppend: function(element, value, master_element) {
//       $('#afile3-list').append('

  • afterFileAppend - ' + value + '

')
//     },


})

- JS - 전송
 $('#fileUploadFrm').ajaxForm({
        contentType : false,
        processData: false,
        enctype: "multipart/form-data",
//         dataType : "POST",
        dataType : 'json',
        beforeSubmit: function(data, form, option) {
            console.log('beforeSubmit');
            console.log(data);
            console.log(form);
            console.log(option);
            isUploadingTrue();
        },
        success: function(data, status, jqxhr) {
         if(data.status != 'success') {
         alert(data.msg);
         }  else {
         alert('수동 적재가 완료되었습니다');
         LxPopup.clearModalPopup(); 
         loadTab4_schedule(); // 스케줄 탭 갱신 - 수집 외 화면에 이 기능 추가시 수정 필요.
         }
        },
        error: function(x, status, error){
         alert("파일 전송중 오류  "+status +'\r\n'+error);
            console.log("파일 전송중 오류  "+status);
//             console.log(e);
//          LxPopup.clearModalPopup(); 
        },
        complete : function() { 
         isUploadingFalse()
        },
        
        beforeSend: function() {
//             status.empty();
            var percentVal = '0%';
            bar.width(percentVal);
            percent.html(percentVal);
        },
        uploadProgress: function(event, position, total, percentComplete) {
            var percentVal = percentComplete + '%';
            bar.width(percentVal);
            percent.html(percentVal);
        }
//         complete: function(xhr) {
//            alert('성공');
//         },
    });


// 2 // 전송
 $('#fileUploadFrm').submit();

- html

* 서버 Spring 코드 
@RequestParam("myFiles") MultipartFile[] multipartFiles
) throws Exception {

for(MultipartFile mf : multipartFiles) {
File targetFile = new File(sPath+"\\"+ mf.getOriginalFilename());
try {
InputStream fileStream = mf.getInputStream();
FileUtils.copyInputStreamToFile(fileStream, targetFile);

} catch (IOException e) {
FileUtils.deleteQuietly(targetFile);

return "ERR";
}



- 기타 고려 사항 1 - 업로드 중 사용 중단   

function isUploadingTrue() {
isUploading = true;
$('.MultiFile-remove input').attr('disabled','');
$('#myFiles').attr('disabled','')
$('.popup_close').attr('onclick','')
}

function isUploadingFalse() {
isUploading = false;
$('.MultiFile-remove input').attr('disabled','');
$('#myFiles').attr('disabled','')
$('.popup_close').attr('onclick','LxPopup.clearModalPopup()')
}



--------------------------- 검색 결과 정리 --------------------------

[[ 파일 업로드 Server단 구현 (Spring Controller)
1. MultipartHttpServletRequest 받아오거나
https://cheonfamily.tistory.com/6
https://aljjabaegi.tistory.com/373

1) Iterator<?> iter = req.getFileNames();
이건 실패..



2. @RequestParam MultiFile[] 로 받아오는 방법



[[ 파일 업로드 Client단 구현 - JQuery
* Jquery 의 MultiFile 플러그인은 검색하면 2가지가 나옴

1. $().MultiFile() (대문자)
http://lampspw.wallonie.be/dgo4/tinymvc/myfiles/plugins/multifile-2.2.1/docs.html#Credit

2. $().multifile() (소문자)
https://www.jqueryscript.net/demo/jQuery-Plugin-For-Selecting-Multiple-Files-multifile/

전자를 많이 사용. 후자와는 완전히 다른것이니 헷갈리지 않아야 함.


* submit 은 다음 방법이 있음
1. form.submit() 직접 실행하는 방법
2. $.ajax() 에 FormData() 이용
https://cheonfamily.tistory.com/6

2. jqury ajaxForm 이용한 방법
https://fruitdev.tistory.com/199

  선언 후 사용



* 업로드 전 파일 미리보기
http://aljjabaegi.tistory.com/384


* 프로그레스바 구현 
https://wondongho.tistory.com/98

* 드래그앤 드롭 멀티파일 업로드
https://cofs.tistory.com/364


[[ 파일 업로드 유효성 체크
* 서버
https://aljjabaegi.tistory.com/373

* 클라이언트 - MultiFile 사이트 참고 

 

공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
TAG
more
«   2024/03   »
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
31
글 보관함