2017-10-29 2 views
1

에 differents의 ID로 업로드 파일 : 하나의 파일 입력과 함께 좋은 작품 http://blog.netgloo.com/2015/02/08/spring-boot-file-upload-with-ajax/배수가 테이블에 코드를 적용하려고

(문제없이 여러 프로젝트에 사용).

내 requeriment는 모든 행에 파일 입력으로 테이블을 만드는 것입니다.

입력 파일의 ID에 코드를 추가합니다. 나중에 내 컨트롤러에서 그 코드를 사용할 것이다.

가 나는 형태의 ID와 입력 할당 한 값에 추가 테이블 (OK)

<div class="table-responsive" 
      th:if="${not #lists.isEmpty(objects)}"> 
      <table id="d" 
       class="table table-hover table-sm table-responsive "> 
       <thead class="thead-inverse"> 
        <tr> 
         <th>Code</th> 
         <th>Name</th> 
         <th>Address</th> 
         <th>Telephone</th> 
         <th>File Upload</th> 
        </tr> 
       </thead> 

       <tbody> 
        <tr th:each="object: ${objects}"> 
         <td th:text="${object.code}"></td> 
         <td th:text="${object.name}"></td> 
         <td th:text="${object.addres}"></td> 
         <td th:text="${object.telephone}"></td> 
         <td> 
          <form th:id="'uploadfileform-' + ${object.code}"> 
           <div class="form-group"> 
            <label class="custom-file"> <input type="file" 
             th:id="'uploadfileinput-' + ${object.code}" 
             name="uploadfile" accept="*" aria-describedby="fileHelp" 
             class="custom-file-input" /> <span 
             class="custom-file-control"></span> 
            </label> 
           </div> 
          </form> 
         </td> 
        </tr> 
       </tbody> 
      </table> 
     </div> 

를 생성한다.

데이터 : 새로운 FormData ($

내 JQuery와

1 부 (OK)

$(document).ready(function() { 
       $('input[type="file"]').change(function(e) { 
        var id = $(this).attr('id'); 
        var res = id.split("-"); 
        // I pass the code 
        uploadFile(res[1]); 
       }); 
     }); 

2 부 (실패)

function uploadFile(id) { 
        $ 
          .ajax({ 
           url : "/uploadFile", 
           type : "POST", 
           data : new FormData($("#uploadfileform"+id)[0]), 
           enctype : 'multipart/form-data', 
           processData : false, 
           contentType : false, 
           cache : false, 
           success : function() { 
            // Handle upload success 
            $("#upload-file-message").text(
              "File succesfully uploaded"); 
            alert("File succesfully uploaded"); 
           }, 
           error : function() { 
            // Handle upload error 
            $("#upload-file-message") 
              .text(
                "File not uploaded (perhaps it's too much big)"); 
            alert("File not uploaded (perhaps it's too much big)"); 
           } 
          }); 
       } // function uploadFile 

나는에 실패 믿는다 ("#uploadfileform"+ id) [0]),

하지만 디버깅 할 수있는 방법이 없습니다.

그리고 이것은 정확하게 블로그처럼, 컨트롤러의 일부입니다 : 내가

을 얻을 두 경우 모두에서

data : new FormData($('input[type="file"]')[0]), 

: 1 개

변경된 데이터

@RequestMapping(value = "/uploadFile", method = RequestMethod.POST) 
    @ResponseBody 
    public ResponseEntity<?> uploadFile(@RequestParam("uploadfile") MultipartFile uploadfile) { 

UPDATE

POST http://localhost:8080/uploadFile 400() 

감사

업데이트 2

$(document).ready(function() { 
       //http://blog.netgloo.com/2015/02/08/spring-boot-file-upload-with-ajax/ 
       $('input[type="file"]').change(function(e) { 

        //var file = $('input[type="file"][0]'); 
        var file = $('input[type="file"]')[0]; 

        alert("File name: " + file.fileName); 
        alert("File size: " + file.fileSize); 

}); 
      }); 

내가 정의되지 않은 얻을, 그래서 이런 종류의 코드는이 상황에 대한 정확하지라고 생각합니다.

+0

안녕하세요, 나는이 줄에 하나의 가능한 오류가 잘 작동'새로운 FormData ($ ("#uploadfileform"+ id) [0])''#uploadfileform - "+ id' (id 앞에 하이픈이 붙어 있음) – Andrea

+0

바뀌 었습니다. data : new FormData ($ ("# uploadfileform -"+ id) [0]), 에러 함수와 콘솔에서 메시지를받습니다 : .wsmsDefaultHandlerExceptionResolver : 처리기 실행으로 인한 해결 된 예외 : org.springframework.web.multipart. support.MissingServletRequestPartException : 요청 부분 'uploadfile'이 필요하지 않습니다. – davisoski

+1

@davisoski, 생성 된 html이 예상대로인지 확인하고 Chrome 네트워크 탭에서 POST 데이터가 정상적으로 작동하는지 확인 할 수 있습니까? –

답변

1

제공하신 코드에 2 가지 문제가 있습니다. 하나는 application.propertiesupload.file.path이 누락되었습니다. 그래서 자바 스크립트 코드

  $('input[type="file"]').change(function(e) { 
       //id is undefined 
       var id = $(this).attr('id'); 

당신이 지정하는 ID가 양식 필드에에서가 아니라 입력에

upload.file.path = ./ 

다음

을 추가했다.그래서 그 두 가지 사항을 변경 한 후

<form th:id="'uploadfileform-'+${directory.code}"> 
    <div class="form-group"> 
     <label class="custom-file"> <input type="file" 
      th:name="uploadfile" accept="*" aria-describedby="fileHelp" 
      class="custom-file-input" th:id="'uploadfileinput-'+${directory.code}"/> <span 
      class="custom-file-control"></span> 
     </label> 
    </div> 
</form> 

<form th:id="'uploadfileform-'+${directory.code}"> 
    <div class="form-group"> 
     <label class="custom-file"> <input type="file" 
      th:name="uploadfile" accept="*" aria-describedby="fileHelp" 
      class="custom-file-input"/> <span 
      class="custom-file-control"></span> 
     </label> 
    </div> 
</form> 

아래에 업데이트가

Working

+0

안녕하세요.

올바르게 코드를 분석하지 않은 코드는 github에서 springboot 프로젝트를 준비합니다. 감사합니다. – davisoski

+0

안녕하세요. 봄 프로젝트를 만들었습니다 : https://github.com/elecdesa/multiple_fileupload 감사합니다 – davisoski

+0

@ davisoski, 정적 파일도 커밋 할 수 있습니까? 페이지가 정확히로드 됨 –

관련 문제