2016-12-06 1 views
0

웹 응용 프로그램에서 POST를 통해 파일을 보내야합니다. 나는 자바에서 서버 측과 앵귤러 2에서 클라이언트 측을 가진다. 나는 클라이언트가 서버에 파일을 보낼 필요가있다. 서버의 코드 :angular2의 파일 보내기

@RequestMapping(method = RequestMethod.POST, value = "/run/file") 
@ResponseBody 
private void runImportRecordsJob(@RequestParam("file") MultipartFile file){ 
    // Some code 
} 

클라이언트의 코드 :

구성 요소 :

export class ImportRecordsJobComponent implements OnInit { 

    file: File; 


    constructor(private jobsService: JobsService) { } 


    chooseFile(event: any){ 
    this.file = event.srcElement.files[0]; 

    console.log(this.file); 
    } 

    selectFormat(event: any){ 
    if (event.length > 0) 
     this.format = event[0].key; 
    else 
     this.format = null; 

    } 

    runImportRecordsJob(){ 
    if (confirm("Are you sure you want to run this job?")){ 
     this.jobsService.runImportRecordsJob({file: this.file}); 
    } 
    } 

    ngOnInit() { 
    } 

} 

서비스 : nested exception is org.springframework.web.multipart.MultipartException: The current request is not a multipart request

A :

@Injectable() 
export class JobsService { 

    constructor(private http: Http) { } 

    runImportRecordsJob(importRecords: any){ 
    var headers = new Headers({"Content-Type": 'application/json; multipart/form-data;'}); 
    let options = new RequestOptions({ headers: headers }); 

    let formData = new FormData(); 
    formData.append("file", importRecords.file, importRecords.file.name); 

    this.http.post(SERVER + "/batches/run/file", formData, options).subscribe(); 
    } 

} 

하지만 오류를 받고 있어요 nd formData은 항상 비어 있습니다. 누구든지 저에게 ng2 업 로더를 사용하지 않고 파일을 보내는 방법을 제안 할 수 있습니까? 감사.

답변

1

"CommonsMultipartResolver"bean을 놓치셨습니까?

<bean id="multipartResolver" 
      class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> 
     <!-- 20 * 1024 * 1024 Byte = 20 MB--> 
     <property name="maxUploadSize" value="20971520" /> 
     <property name="defaultEncoding" value="UTF-8" /> 
    </bean> 

편집 : 서비스에

변경된 방법 :

runImportRecordsJob(importRecords: any){ 
    let options = new RequestOptions(); 

    let formData = new FormData(); 
    formData.append("file", importRecords.file, importRecords.file.name); 

    console.log(formData); 
    console.log(importRecords); 
    this.http.post(SERVER + "/batches/run/file", formData, options).subscribe(); 
    } 
+0

아니, 난 구성한 빈 : \t'@Bean \t 공공 CommonsMultipartResolver multipartResolver() { \t \t CommonsMultipartResolver commonsMultipartResolver = n ew CommonsMultipartResolver(); \t \t commonsMultipartResolver.setDefaultEncoding ("utf-8"); \t \t commonsMultipartResolver.setMaxUploadSize (50000000); \t \t return commonsMultipartResolver; \t} –

+0

var headers = new 헤더 ({ "Content-Type": 'application/json; 다중 파트/양식 데이터;'}); – chaoluo

+0

응용 프로그램 헤더를 제거 할 수 있습니까? – chaoluo