前提・実現したいこと。
javaでcsvファイルを読み込んでブラウザに返却をしたいです。
そして、その返却をしたcsvをダウンロードしたいです。
TypeScriptで書いたコードでダウンロードをすると何も書かれていないファイルがダウンロードされます。
フロントエンドはAngularを使用しています。
CSVの読み込みと返却
CSVの読み込みは以下です。
package csv.opereta; import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; public class CsvReader { public static byte[] Reading() throws Exception { byte[] b = new byte[1]; File file = new File("save.csv"); FileInputStream input = new FileInputStream(file); ByteArrayOutputStream baos = new ByteArrayOutputStream(); while (input.read(b) > 0) { baos.write(b); } baos.close(); input.close(); b = baos.toByteArray(); return b; } }
@Path("csv-down") @Produces("text/csv") @GET public byte[] CsvDownload() throws Exception { byte[] i = CsvReader.Reading(); return i; }
TypeScript
public async outputCsv(event: any): Promise<any> { this.http.getCsv() .then( (response: any) => { const csv = response.csv; const filename = response.fileName; console.log('responce', response) const bom = new Uint8Array([0xEF, 0xBB, 0xBF]); const blob = new Blob([bom, csv], { type: 'text/csv' }); const url = window.URL.createObjectURL(blob); const link: HTMLAnchorElement = this.element.querySelector('#csv-donwload') as HTMLAnchorElement; link.href = url; link.download = filename; link.click(); } ) .catch( (error) => console.log(error) ); }
public getCsv(): Promise<any> { return this.http.get(this.host + 'csv-down', this.httpOptions) .toPromise() .then((res) => { const response: any = res; console.log('aaa', response) return response; }) .catch(this.handleError); }
### わからないこと。質問。
>CSVファイルはbyte[]で読み込んで返却をしていいのか?
>TypeScriptで返却されたbyte型のcsvデータが読み込めていないのか?
>RXJSでは返却されたデータをどのように扱っていくのか?
上記がわかりません。
一般的にどのような方法で実装をしていくのかを教えていただけたら幸いです。
あなたの回答
tips
プレビュー