前提・実現したいこと
サーバサイド: Spring Boot
フロントエンド: Angular5
画像のアップロード機能を実装するために、multipart request での通信を実装したいのですが、Angular側の書き方がわからず困っています。
詳細は下記の通りなので、分かる方ご教授よろしくお願いします。
発生している問題・エラーメッセージ
いつも通りの通信を行おうとした場合、
org.springframework.web.multipart.MultipartException: Current request is not a multipart request
と言ったように、multipart request ではないという表示が出ます。これは、Content-Type が application/json のためだと考えました。
したがって、Content-Type を multipart/form-data に変更してから通信を行ったところ、
org.apache.tomcat.util.http.fileupload.FileUploadException: the request was rejected because no multipart boundary was found
というエラーが表示されます。
調べたところ、multipart request で通信を行う場合、ヘッダに boudary というのを加えなくてはいけないようなのですが、値は自動で生成される値なので、自分で設定することもできません。
Angular5 での通信方法がわからず質問した次第です。
該当のソースコード
typeScript
1pushFileToStorage(file: File, http: HttpClient) { 2 let formdata: FormData = new FormData(); 3 formdata.append('file', file); 4 this.headers = this.headers.set('X-XSRF-TOKEN', this.cookieService.get('XSRF-TOKEN')); 5 // this.headers = this.headers.set('Content-Type', 'application/json'); 6 this.headers = this.headers.set('Content-Type', 'multipart/form-data'); 7 http.post(this.hostname + "settings/me/icon", formdata, { withCredentials: true, headers: this.headers, responseType: 'text'}).subscribe( 8 id => { 9 }, 10 error => { 11 } 12 ); 13 }
java
1@PostMapping(value = "me/icon") 2@ResponseStatus(HttpStatus.CREATED) 3public ResponseEntity<String> handleFileUpload(@AuthenticationPrincipal User user, @RequestParam("file") MultipartFile file) { 4 String message = ""; 5 try { 6 settingLogic.store(user.getEmployeeNumber(), file); 7 files.add(file.getOriginalFilename()); 8 message = "You successfully uploaded " + file.getOriginalFilename() + "!"; 9 return ResponseEntity.status(HttpStatus.OK).body(message); 10 } catch (Exception e) { 11 message = "FAIL to upload " + file.getOriginalFilename() + "!"; 12 return ResponseEntity.status(HttpStatus.EXPECTATION_FAILED).body(message); 13 } 14}
以上になります。よろしくお願いします。
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2018/03/16 05:52