I have method on the Spring server which requires user token to allow downloading the resource. The resource is sent by url in TextView. When I click the url, the browser opens, but obviously without any header added. How can I add a header with a token to my request? Or how can I handle this web browser event to call my own function with the header added?
I have done a lot of research but couln't find the answer.
Here is my /download method at Spring server
@RequestMapping(value = "/download/{name:.+}", method = RequestMethod.GET)
public HttpEntity<?> downloadFile (@RequestHeader("token") String token,
@PathVariable("name") String name,
final HttpServletRequest request, final HttpServletResponse response) throws IOException {
if (tokenRepository.findByKeyVal(token) == null) {
return null;
}
User userFrom = userRepository.findByToken(token);
if(name.contains("_"+ userFrom.getId() +"_")){
// files names are saved in timestap + _user1+_user2 format//
Resource resource;
Path path = Paths.get(uploadDir + name);
try {
resource = new UrlResource(path.toUri());
} catch (MalformedURLException e) {
e.printStackTrace();
return null;
}
// Try to determine file's content type
String contentType = null;
try {
contentType = request.getServletContext().getMimeType(resource.getFile().getAbsolutePath());
} catch (IOException ex) {
System.out.println("Could not determine file type.");
}
// Fallback to the default content type if type could not be determined
if (contentType == null) {
contentType = "application/octet-stream";
}
return ResponseEntity.ok().contentType(MediaType.parseMediaType(contentType))
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"")
.body(resource);
}
else return new ResponseEntity<String>("Unauthorized", HttpStatus.UNAUTHORIZED);
}
Aucun commentaire:
Enregistrer un commentaire