spring-attic / tut-react-and-spring-data-rest

React.js and Spring Data REST :: A tutorial based on the 5-part blog series by Greg Turnquist
https://spring.io/guides/tutorials/react-and-spring-data-rest
882 stars 1.57k forks source link

File extension is cut off in RequestMapping #63

Closed loudking closed 7 years ago

loudking commented 7 years ago

Hi, may I ask how to disable spring boot from cutting off file extension with RequestMapping please?

My code:

    @RequestMapping(value = "/uploaded/{filename}", method = RequestMethod.GET)
    public ResponseEntity<byte[]> getUploaded(@PathVariable String filename) throws IOException {
        logger.debug("getUploaded filename=" + filename);

        HttpHeaders httpHeaders = new HttpHeaders();
        Resource file = storageService.loadAsResource(filename);
        InputStream inputStream = file.getInputStream();
        byte[] data = IOUtils.toByteArray(inputStream);
        httpHeaders.setCacheControl(CacheControl.noCache().getHeaderValue());

        return new ResponseEntity<>(data, httpHeaders, HttpStatus.OK);
    }

With request: localhost:8080/uploaded/a.png or localhost:8080/uploaded/b.jpg

I got logging:

getUploaded filename=a
getUploaded filename=b

So obviously the file extension is removed by spring boot. How to fix this please?

gregturn commented 7 years ago

By default, Spring MVC uses the suffix for content negotiation. .xml renders an XML response, .json renders a JSON response.

To overcome, you have to use a pattern like {filename:.+}.

jesperdj commented 3 years ago

You can also prevent this by switching off suffix pattern matching.

See: https://docs.spring.io/spring-framework/docs/4.3.26.RELEASE/spring-framework-reference/html/mvc.html#mvc-config-path-matching

Include in your configuration:

@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {

    @Override
    public void configurePathMatch(PathMatchConfigurer configurer) {
        configurer.setUseSuffixPatternMatch(false);
    }
}

or (XML):

<mvc:annotation-driven>
    <mvc:path-matching suffix-pattern="false"/>
</mvc:annotation-driven>