Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
410 views
in Technique[技术] by (71.8m points)

javascript - Download a file from spring boot rest services from angular 5

I have spring boot service which provides csv file as response. How do we call this service from angular 5 typescript. download of a file should happen depends on some input parameters so I will have post call with user clicks the export button.

below is the rest code in controller.

@Controller
public class MyController {

 @RequestMapping(value = "/downLoadDataQueryCsv", method = RequestMethod.GET)
    public ResponseEntity<Object> downLoadDataQueryCsv(Model model) throws IOException  {
        FileWriter fileWriter = null;
        try {
            DataQueryRequestParams dataQueryRequestParams = new DataQueryRequestParams();
            dataQueryRequestParams.setMbuCategory("UKY");
            // Result table.
            List<OrderIdFinalRank> rankList =  // call api to get data.
            // construct headers
            List<String> csvHeaders = constructDataQueryHeaders();
            StringBuilder fileContent = new StringBuilder(String.join(",", csvHeaders));
            fileContent.append("
");
            // construct file content from response  
            for(OrderIdFinalRank finalRank : rankList)  {
                fileContent.append(StringUtils.join(constructDataQueryRow(finalRank), ",")).append("
");
            }
            String fileName = new String("DataQueryTab.csv");
            fileWriter = new FileWriter(fileName);
            fileWriter.write(fileContent.toString());
            fileWriter.flush();

            File file = new File(fileName);

            InputStreamResource resource = new InputStreamResource(new FileInputStream(file));
            HttpHeaders headers = new HttpHeaders();
            headers.add("Content-Disposition", String.format("attachment; filename="%s"", file.getName()));
            headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
            headers.add("Pragma", "no-cache");
            headers.add("Expires", "0");

            ResponseEntity<Object> responseEntity = ResponseEntity.ok().headers(headers).contentLength(file.length())
                    .contentType(MediaType.parseMediaType("application/txt")).body(resource);
            return responseEntity;
        } catch (Exception e) {
            System.out.println("Exception: " +e);
            return new ResponseEntity<>("Error occurred", HttpStatus.INTERNAL_SERVER_ERROR);
        } finally {
            if(null != fileWriter)  {
                fileWriter.close();
            }
        }
    }
    }

Now I need to call this from UI when I click export button, what have written is below.

I have read file saver and added below code, but its not working. kindly help me.

@Injectable()
export class ApiService { 
onExport(dataQueryRequestParams: any) {
    const dataQueryURL = API_URL + '/downLoadDataQueryCsv';
    const body = JSON.stringify(dataQueryRequestParams);
    this._http.get(dataQueryURL).subscribe(res => {
      saveAs(res, 'data.csv');
    });
  }
    }

Note: When I ran rest URL from browser the file is downloaded, but the same needs to happen when I click export button.

Am new to UI technologies. Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I have fixed problem with below code.

export class ApiService {
 onExport(requestParams: any): Observable<any> {
    const dataQueryURL = API_URL + '/downLoadDataQueryCsv';
    const httpOptions = {
      headers: new HttpHeaders({
        'Content-Type': 'Application/json; charset=UTF-8'
      }),
      responseType: 'text' as 'text'
    };
    const body = JSON.stringify(requestParams);
    return this._http.post(dataQueryURL, body, httpOptions);
  }
}

added below in caller Component class.

  export class Component implements OnInit {
     onExport() {        this._apiService.onExport(this.dataQueryForm.value).subscribe(data => {
          const blob1 = new Blob([data], { type: 'text/csv' });
          FileSaver.saveAs(blob1, 'data.csv');
        }) ;
      }
    }

Thank you all for your responses !


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...