I am uploading zip folder from screen and I am sending it to contoller using MultipartFile.I am trying to extract the uploaded folder and saving that extracted folder in some specific location..I tried but I am not getting....Can anyone suggest me? here is my code
public String test(
@RequestParam("datafile") MultipartFile file
{
String source =file.getOriginalFilename();
//source variable will containthe value as "zip_Folder.zip";
String destination = "D:\\destination";
try {
ZipFile zipFile = new ZipFile(source);
zipFile.extractAll(destination);
} catch (ZipException e) {
e.printStackTrace();
}
}
To unzip a zip file, we need to read the zip file with ZipInputStream and then read all the ZipEntry one by one. Then use FileOutputStream to write them to file system. We also need to create the output directory if it doesn't exists and any nested directories present in the zip file.
Do one of the following: To unzip a single file or folder, open the zipped folder, then drag the file or folder from the zipped folder to a new location. To unzip all the contents of the zipped folder, press and hold (or right-click) the folder, select Extract All, and then follow the instructions.
Methods. getComment(): String – returns the zip file comment, or null if none. getEntry(String name): ZipEntry – returns the zip file entry for the specified name, or null if not found. getInputStream(ZipEntry entry) : InputStream – Returns an input stream for reading the contents of the specified zip file entry.
ZIP is a common file format that compresses one or more files into a single location. It reduces the file size and makes it easier to transport or store. A recipient can unzip (or extract) a ZIP file after transport and use the file in the original format.
Required zip4j and Apache Commons-IO dependencies:
@PostMapping("/upload")
public String add(@RequestParam("file") MultipartFile file) throws IOException {
/**
* save file to temp
*/
File zip = File.createTempFile(UUID.randomUUID().toString(), "temp");
FileOutputStream o = new FileOutputStream(zip);
IOUtils.copy(file.getInputStream(), o);
o.close();
/**
* unizp file from temp by zip4j
*/
String destination = "D:\\destination";
try {
ZipFile zipFile = new ZipFile(zip);
zipFile.extractAll(destination);
} catch (ZipException e) {
e.printStackTrace();
} finally {
/**
* delete temp file
*/
zip.delete();
}
return "redirect:/";
}
As addition to that, the best is to place constants like "D:\destination" in properties file and inject by @Value
@Value("${destination.dir}")
private String destination;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With