###### tags: `Angular` `Image` # 🌝[T]Image ## 圖片更新 html ```htmlmixed <!-- 上傳圖片 --> <tr> <th>上傳圖片</th> <td><input type="file" id="img_up" name="img_up" (change)="onClickUpload($event)"/></td> </tr> ``` typescript ```typescript /**圖片上傳*/ onClickUpload(event: any) { const eventObj: MSInputMethodContext = <MSInputMethodContext>event; const target: HTMLInputElement = <HTMLInputElement>eventObj.target; const file: FileList = target.files; this.file = file[0]; } onSubmit () { // 圖片更新 const parameter = new ApiParameter(TableApiName.OMMDAA, [TableApiParameter.Photo]); const formData = new FormData(); const header = new HttpHeaders({ 'Authorization': localStorage.getItem('auth_token') }); /*PhotoFile後端給*/ formData.append('PhotoFile', this.file); if (!!this.file) { /*parameter=API接腳 / fromData=資料 / header=Request-Headers*/ this.apiTableService.updateDataParameter(parameter, formData, false, {headers: header}).subscribe(() => { // 重新載入 alert('會員資料更新完成'); window.location.reload(); }); } else { // 重新載入 alert('會員資料更新完成'); window.location.reload(); } } ``` ## 錯誤集 ### #快取 JavaScript快取會依檔名是否相同來看是否要重抓檔案,導致更新後圖片依舊是舊的圖片。 若想從前端這邊解決此問題,可以從後端回傳的資料動手腳 typescript ```typescript this.member.Photo = this.memberReg.Photo ? this.member.Photo + `?v=${new Date().getTime()}` : this.memberReg.Photo; ``` ### #Content-Type格式錯誤 :::warning **⚡415 Unsupported Media Type** ::: 表示被請求資源的多媒體類型不被伺服器支援,因此該請求被拒絕。 依圖片來說,傳送的型態是FormData,但Conent-Type這邊卻是application/json就會有問題。 [HTML forms provide three methods of encoding.](https://stackoverflow.com/questions/4526273/what-does-enctype-multipart-form-data-mean) :::spoiler 圖 Content-Type: applicate/json  ::: 正常來說HTTP會依照傳送的資料型態自己給Conent-Type,由於我們的程式內有寫Interceptor,若沒有特別給header的時候會預設Conent-Type: applicate/json,為了能順利傳圖片,我們在程式call API的時候 new HttpHeaders給HTTP就不會給預設值了。 ```typescript const header = new HttpHeaders({ 'Authorization': localStorage.getItem('auth_token') }); ``` :::spoiler 圖 Content-Type: mutipart/form-data  :::
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up