Reputation: 3340
I need an API that will let me download a (e.g. CSV file). I tried to do something like this:
@RequestMapping(value="/{cartId}/export", method = RequestMethod.GET, produces = { "application/octet-stream" })
@ApiOperation(hidden = false, value = "Exports the contents of a cart as a CSV file.", notes = "Exports the contents of a cart as a CSV file.")
@ApiBaseSiteIdUserIdAndCartIdParam
public @ResponseBody ResponseEntity export() {
File file = new File("test.csv");
return ResponseEntity.ok()
.header("Content-Disposition", "attachment; filename=" + "test" + ".csv")
.contentLength(file.length())
.contentType(MediaType.parseMediaType("application/octet-stream"))
.body(new FileSystemResource(file));
}
However, I would get errors like this:
0203_17:48:01,878 INFO [hybrisHTTP21] [de.hybris.platform.webservicescommons.resolver.RestHandlerExceptionResolver.doResolveException:73] Translating exception [org.springframework.web.HttpMediaTypeNotAcceptableException]: Could not find acceptable representation 0203_17:48:01,879 WARN [hybrisHTTP21] [de.hybris.platform.webservicescommons.resolver.AbstractRestHandlerExceptionResolver.writeWithMessageConverters:72] Could not find HttpMessageConverter that supports return type [class de.hybris.platform.webservicescommons.dto.error.ErrorListWsDTO] and [application/octet-stream] 0203_17:48:01,879 WARN [hybrisHTTP21] [org.springframework.web.servlet.handler.AbstractHandlerExceptionResolver.logException:197] Resolved [org.springframework.web.HttpMediaTypeNotAcceptableException: Could not find acceptable representation]
I understand this is because springmvc-servlet.xml only has resolverXStreamJSONConverter and resolverXStreamXmlConverter.
If I were to do it the MVC way, I'd write the file to a HttpServletResponse, but that doesn't seem ideal for OCC. So, how should I implement the file download? (Code sample also appreciated)
NOTE: The API/method will be used with Spartacus storefront.
Upvotes: 1
Views: 944
Reputation: 13
I needed a similar implementation to offer a PDF download. The controller now returns ResponseEntity<byte[]>
and I appended the corresponding MessageConverter. I also didnt find a 'better' way, but it works.
<bean id="myByteArrayHttpMessageConverter" class="org.springframework.http.converter.ByteArrayHttpMessageConverter"/>
<bean depends-on="messageConvertersV2" parent="listMergeDirective">
<property name="add" ref="myByteArrayHttpMessageConverter"/>
</bean>
Upvotes: 1
Reputation: 3340
A workaround is to add org.springframework.http.converter.ResourceHttpMessageConverter in messageConvertersV2 in web/webroot/WEB-INF/config/v2/jaxb-converters-spring.xml:
<util:list id="messageConvertersV2">
<bean class="org.springframework.http.converter.ResourceHttpMessageConverter"/>
<ref bean="customJsonHttpMessageConverter"/>
<ref bean="customXmlHttpMessageConverter"/>
</util:list>
However, not sure if this is correct or a good idea.
Upvotes: 1