How to Crate Folder Upload in Java
Simplest and Easy style to Upload and Download Files in Java with Leap Boot
August i, 2018 Coffee, How To Guide
Uploading and Downloading Files is ane of the core functionality that any Enterprise Application wants to incorporate. In this article, we will run into How to Upload and Download Files in Coffee with Bound Boot.
Softwares used
- Spring Boot 2.0.iii.RELEASE
- Thymeleaf
- Java eight
- Maven
- Eclipse
Maven Dependencies
Below are the key dependencies that we are using.
1 2 3 4 5 6 vii eight ix x 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | < properties > < project . build . sourceEncoding > UTF - 8 < / project . build . sourceEncoding > < project . reporting . outputEncoding > UTF - viii < / project . reporting . outputEncoding > < java . version > 1.8 < / java . version > < maven - jar - plugin . version > 2.6 < / maven - jar - plugin . version > < / properties > < dependencies > < dependency > < groupId > org . springframework . boot < / groupId > < artifactId > jump - kicking - starter - thymeleaf < / artifactId > < / dependency > < dependency > < groupId > org . springframework . kicking < / groupId > < artifactId > leap - kicking - starter - spider web < / artifactId > < / dependency > < dependency > < groupId > org . springframework . boot < / groupId > < artifactId > spring - boot - starter - test < / artifactId > < telescopic > test < / scope > < / dependency > < ! -- WebJars -- > < dependency > < groupId > org . webjars < / groupId > < artifactId > bootstrap < / artifactId > < version > three.3.6 < / version > < / dependency > < dependency > < groupId > org . webjars < / groupId > < artifactId > jquery < / artifactId > < version > 2.one.4 < / version > < / dependency > < ! -- / WebJars -- > < / dependencies > |
Our code is built on peak of Web Starter Application. We are using WebJars for Bootstrap and Jquery.
At the cadre of this awarding volition be our service form – FileSystemStorageService.coffee. We will look at each of its functions in the residual of the article.
Initialization
@ PostConstruct public void init ( ) { this . uploadLocation = Paths . get ( Constants . UPLOAD_LOCATION ) ; try { Files . createDirectories ( uploadLocation ) ; } take hold of ( IOException e ) { throw new RuntimeException ( "Could non initialize storage" , due east ) ; } } |
This code is executed after the service course object is created. In this init method, we attempt to create the directory where we desire to upload our files.
Storing the file
1 two three 4 five 6 7 8 9 10 xi 12 13 14 15 16 17 xviii 19 | public void store ( MultipartFile file ) { String filename = StringUtils . cleanPath ( file . getOriginalFilename ( ) ) ; endeavour { if ( file . isEmpty ( ) ) { throw new RuntimeException ( "Failed to store empty file " + filename ) ; } // This is a security check if ( filename . contains ( ".." ) ) { throw new RuntimeException ( "Cannot shop file with relative path outside current directory " + filename ) ; } endeavour ( InputStream inputStream = file . getInputStream ( ) ) { Files . re-create ( inputStream , this . uploadLocation . resolve ( filename ) , StandardCopyOption . REPLACE_EXISTING ) ; } } catch ( IOException e ) { throw new RuntimeException ( "Failed to shop file " + filename , east ) ; } } |
This method will go a MultipartFile from Spring controller. The file name is then resolved relative to our upload directory and copied there.
File as Resources
public Resources loadAsResource ( String filename ) { try { Path file = uploadLocation . resolve ( filename ) ; Resource resource = new UrlResource ( file . toUri ( ) ) ; if ( resource . exists ( ) || resource . isReadable ( ) ) { return resource ; } else { throw new RuntimeException ( "Could not read file: " + filename ) ; } } take hold of ( MalformedURLException east ) { throw new RuntimeException ( "Could not read file: " + filename , e ) ; } } |
Above lawmaking, converts a file that we desire to download into a Resource. This resource is later pushed to download via the controller.
Now permit us look at few controller methods which utilize above service course to reach the functionality.
Handle File Upload
@ RequestMapping ( value = "/files/upload" , method = RequestMethod . POST ) public String handleFileUpload ( @ RequestParam ( "file" ) MultipartFile file , RedirectAttributes redirectAttributes ) { storageService . store ( file ) ; redirectAttributes . addFlashAttribute ( "message" , "You successfully uploaded " + file . getOriginalFilename ( ) + "!" ) ; return "redirect:/" ; } |
Above method will boot off, when you lot upload a file from UI. The Spring controller receives a MultipartFile, which is then sent to storage service class.
Downloading a File
one 2 3 four 5 6 7 8 9 10 11 12 13 fourteen fifteen 16 17 eighteen 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | @ RequestMapping ( value = "/files/list" , method = RequestMethod . Become ) public Cord listFiles ( Model model ) { List < Path > lodf = new ArrayList <> ( ) ; List < HRefModel > uris = new ArrayList <> ( ) ; try { lodf = storageService . listSourceFiles ( storageService . getUploadLocation ( ) ) ; for ( Path pt : lodf ) { HRefModel href = new HRefModel ( ) ; href . setHref ( MvcUriComponentsBuilder . fromMethodName ( UploadController . form , "serveFile" , pt . getFileName ( ) . toString ( ) ) . build ( ) . toString ( ) ) ; href . setHrefText ( pt . getFileName ( ) . toString ( ) ) ; uris . add ( href ) ; } } catch ( IOException e ) { // TODO Auto-generated take hold of block e . printStackTrace ( ) ; } model . addAttribute ( "listOfEntries" , uris ) ; render "file_list :: urlFileList" ; } @ GetMapping ( "/files/{filename:.+}" ) @ ResponseBody public ResponseEntity < Resource > serveFile ( @ PathVariable String filename ) { Resource file = storageService . loadAsResource ( filename ) ; return ResponseEntity . ok ( ) . header ( HttpHeaders . CONTENT_DISPOSITION , "attachment; filename=\"" + file . getFilename ( ) + "\"" ) . trunk ( file ) ; } |
Downloading a file is 2 step procedure. First, we have to list all the files in the URL form and when the user clicks on any of the links, we will ship the actual file.
Listing of files uses MvcUriComponentsBuilder to prepare the URL based on the method which is going to actually serve the file for download. When a user clicks on a file name headers and attachments is sent to the client.
Demo: Upload and Download Files in Java
Notice that we are allowing just text files to be uploaded. The upload push is enabled just when a user selects text file. The lawmaking for this is bachelor in upload.js.
In one case you select a text file and click on Upload, you will meet the message that file is uploaded successfully.
You can check the files which we uploaded and listed on our page are physically available on our servers.
Determination
In this article, we have seen how Spring Boot has fabricated Upload and Download Files in Java easy to implement.
The consummate code is available at our GitHub repo. Delight feel free to download and try.
Download Code
Source: https://www.opencodez.com/java/file-upload-and-download-in-java-spring-boot.htm
0 Response to "How to Crate Folder Upload in Java"
Post a Comment