Angular 2 downloading a file: corrupt result

后端 未结 2 948
走了就别回头了
走了就别回头了 2020-12-30 12:52

I am attempting to download a file using Angular 2/TypeScript and Web API. The problem I am having is that when downloading the text file, the file is file but when attempti

2条回答
  •  梦毁少年i
    2020-12-30 13:01

    We were having a similar issue and had to configure a messageConverter on the spring side. The code snippet below is from Spring config file :-

        @Override
         public void configureMessageConverters(List> 
             converters) {
        //Here we add our custom-configured HttpMessageConverter
       /* Message converter for supporting Hibernate lazy objects */
        converters.add(jacksonMessageConverter());
        converters.add(byteArrayHttpMessageConverter());
        super.configureMessageConverters(converters);
    }
    
        public ByteArrayHttpMessageConverter byteArrayHttpMessageConverter() {
        ByteArrayHttpMessageConverter arrayHttpMessageConverter = new ByteArrayHttpMessageConverter();
        arrayHttpMessageConverter.setSupportedMediaTypes(getSupportedMediaTypes());
        return arrayHttpMessageConverter;
    } 
    
    private List getSupportedMediaTypes() {
        List list = new ArrayList();
        list.add(MediaType.APPLICATION_OCTET_STREAM);
        list.add(MediaType.parseMediaType("application/pdf"));
        return list;
    }
    

    More details on configuring message converters can be found here:- http://www.baeldung.com/spring-httpmessageconverter-rest

    You still need to add the "Accept" header in the request as answered by Chris. This will help map the response to an appropriate message converter configured on the spring side.

提交回复
热议问题