How to expose an resource like downloadable link in Spring boot

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP


How to expose an resource like downloadable link in Spring boot



Actually I have a spring boot server with many files in resource folder (src/main/resources/public/myfilefolder/myfiles.apk). Well my requirement is to download a file with cordova file transfer library. My first idea was put the resource link directly in the component:


var fileTransfer = new FileTransfer();
var fileURL = "///storage/emulated/0/DCIM/myFile";
var uri = encodeURI("http://myserver/src/main/resources/public/myfilefolder/myfiles.apk");

fileTransfer.download(
uri,
fileURL,
function(entry) {
alert("download complete: " + entry.toURL());
},
function(error) {
alert("download error source " + error.source);
alert("download error target " + error.target);
alert("download error code" + error.code);
},
false,
{

/*
headers: {
"Authorization": "Basic dGVzdHVzZXJuYW1lOnRlc3RwYXNzd29yZA=="
}

*/
}



But obviously doesn´t work well, because the server think that it´s a controller route. Any ideas to expose this resource to be downloadable?





The URL is http://myserver/myfilefolder/myfiles.apk. Documentation: docs.spring.io/spring-boot/docs/current/reference/htmlsingle/…
– JB Nizet
7 mins ago




http://myserver/myfilefolder/myfiles.apk





Yes men.... this was the solution, ty for save my day
– Jose Ahías Vargas
2 mins ago




1 Answer
1



You can expose a get request in springboot app where you can pass your file name and it will download the file as based on input, you can add restriction on download based on your application requirement.


@GetMapping("/downloadResource")
public ResponseEntity<ByteArrayResource> downloadResource(
@RequestParam(defaultValue = DEFAULT_FILE_NAME) String fileName) throws IOException {

MediaType mediaType = MediaTypeUtils.getMediaTypeForFileName(this.servletContext, fileName);
System.out.println("fileName: " + fileName);
System.out.println("mediaType: " + mediaType);

Path path = Paths.get(DIRECTORY + "/" + DEFAULT_FILE_NAME);
byte data = Files.readAllBytes(path);
ByteArrayResource resource = new ByteArrayResource(data);

return ResponseEntity.ok()
// Content-Disposition
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + path.getFileName().toString())
// Content-Type
.contentType(mediaType) //
// Content-Lengh
.contentLength(data.length) //
.body(resource);
}






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

Keycloak server returning user_not_found error when user is already imported with LDAP

PHP parse/syntax errors; and how to solve them?

How to scale/resize CVPixelBufferRef in objective C, iOS