2016-12-06 6 views
0

WebアプリケーションでPOST経由でファイルを送信する必要があります。私はJavaのサーバー側と角度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

@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戻り値commonsMultipartResolver; \t} –

+0

var headers = newヘッダー({"Content-Type": 'application/json; multipart/form-data;'}); – chaoluo

+0

アプリケーションヘッダーを削除できますか? – chaoluo

関連する問題