I'm using Spring MVC, I want to display PDF file from my local to webpage. I don't know what should I do to my controller to do this. I see some similar problem with an answer that returning a ResponseEntity<byte[]>
like in this question but this one is for ajax
if I'm not mistaken, this is not my requirement.
Update:
This is what I tried so far:
<a href="#" onClick="test();" >test</a>
function test(){
$.ajax({
type: "POST",
url: "../admin/module/id.do",
data: '{ file_id }',
success: function(response){
alert(response);
}
});
}
And the controller:
@RequestMapping( value = "/admin/module/id", method = RequestMethod.POST )
public ResponseEntity<byte[]> getPDF( @PathVariable( "id" )
int id, Model model )
{
System.out.println( "test" );
Path path = Paths.get( "C:/Users/FORSAK~1/AppData/Local/Temp/spring_tutorial.pdf" );
byte[] contents = null;
try
{
contents = Files.readAllBytes( path );
}
catch( IOException e )
{
e.printStackTrace();
}
HttpHeaders headers = new HttpHeaders();
headers.setContentType( MediaType.parseMediaType( "application/pdf" ) );
String filename = "spring_tutorial.pdf";
headers.setContentDispositionFormData( filename, filename );
ResponseEntity<byte[]> response = new ResponseEntity<byte[]>( contents, headers, HttpStatus.OK );
return response;
}
the alert(response)
doesn't work and also the System.out.println( "test" );
The error from the firebug is "NetworkError: 500 Internal Server Error - http://localhost:8080/ThesisProject/admin/module/id.do"
Stacktrace:
java.lang.IllegalStateException: Could not find @PathVariable [id] in @RequestMapping
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter$ServletHandlerMethodInvoker.resolvePathVariable(AnnotationMethodHandlerAdapter.java:857)
at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.resolvePathVariable(HandlerMethodInvoker.java:710)
at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.resolveHandlerArguments(HandlerMethodInvoker.java:360)
at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:171)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:444)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:432)
....