2017-10-10 3 views
0

형식 파일 형식을 게시하고 JSON 데이터를 반환하여 스프링 부트 컨트롤러에서 해당 POST 요청을 처리하고 있습니다. 나는 그것이 제대로 작동 우체부와 그 요구를 확인,하지만 난에 방법을 onreadystatechange 사용하고 때 XHR 상태를주고 반응 = 0응답의 Xhr 상태가 200 대신 0을 표시합니다.

onSubmitForm(){ 
    console.log("entered"); 
    var xhr = new XMLHttpRequest(); 
    xhr.open('POST', '/images', true); 
    //xhr.responseType = 'text'; 

    xhr.setRequestHeader('Content-type','application/x-www-form-urlencoded'); 

    var data = new FormData(); 
    var imageFile = document.querySelector('input[type="file"]').files[0]; 
    console.log(imageFile); 

    data.append("imageFile", imageFile); 


    xhr.onreadystatechange = function() { 
     if(xhr.readyState === XMLHttpRequest.DONE){ 
      alert(xhr.status); 
      if(xhr.status === 200){ 
       alert('hi there'); 
       } 
     } 
    } 
    xhr.send(data); 

} 

render() { 
    return (
     <div> 
      <form encType="multipart/form-data" action=""> 
       File to upload: 
        <input type="file" name="imageFile" accept="image/*" /> 
        <input type="submit" value="Upload" onClick={ this.onSubmitForm.bind(this) } /> 
      </form> 
     </div> 
    ) 
} 

내가 컨트롤러에서 올바른 데이터를 수신하고,하지만 POST에서 JSON을 받고 있지 않다 요청 ??

컨트롤러

@PostMapping("/images") 
public @ResponseBody JSONModel addContent(@RequestParam("imageFile") MultipartFile file, 
     imageApp content) { 

    String encodedfile = null ; 
    double fileSize = file.getSize(); 

    try { 
      byte[] bytes=file.getBytes(); 
      System.out.println(fileSize/(1024*1024)); 
      encodedfile = Base64.getMimeEncoder().encodeToString(bytes); 
    } catch (FileNotFoundException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } catch (IOException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 

    content.setDate(LocalDateTime.now()); 

    content.setLocation(UUID.randomUUID().toString()); 
    content.setId(UUID.randomUUID().toString()); 
    content.setContent(encodedfile); 
    return service.addContent(content); 
    } 

서비스

public @ResponseBody JSONModel addContent(imageApp content) { 
    return new JSONModel(1, respository.save(content).getLocation()); 
} 
+0

https://stackoverflow.com/questions/872206/http-status-code를 확인할 수 있습니까? -0-what-does-this-for-fetch-or-xmlhttprequest 컨트롤러에 충돌합니까? –

+0

예 타격 @AmitKBist –

+0

컨트롤러에서 무엇을 반환합니까? 귀하의 컨트롤러 코드도 붙여 넣으십시오. –

답변

0

이 유형 = "제출"유지, <input type="submit" to type="button" 확인 페이지/양식을 제출해야하는 브라우저에 지시하며 충돌하는 행동을 유발하는 우리는 예방할 필요가 있습니다. 따라서 type = "button"을 변경하거나 처리기 및 호출에서 이벤트를 가져 와서 기본 동작을 방지 할 수 있습니다. e.preventDefault();

관련 문제