Я делаю zip-загрузку. Мой код работает правильно.
Вот мой код.
package com.example.controller;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.core.io.ClassPathResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import com.example.common.CommonException;
import net.lingala.zip4j.ZipFile;
@Controller
@RequestMapping("/example")
public class ExampleController {
@RequestMapping(value="/myDownload", method = RequestMethod.GET)
public ResponseEntity<byte[]> myDownload(HttpServletRequest request) throws CommonException {
HttpHeaders headers = new HttpHeaders();
ResponseEntity<byte[]> result = null;
try {
ClassPathResource myShareDir1CPR = new ClassPathResource("static/share1");
ClassPathResource myShareDir2CPR = new ClassPathResource("static/share2");
ClassPathResource myShareDir3CPR = new ClassPathResource("static/share3");
ClassPathResource myShareDir4CPR = new ClassPathResource("static/share4");
File share1Dir = myShareDir1CPR.getFile();
File share2Dir = myShareDir2CPR.getFile();
File share3Dir = myShareDir3CPR.getFile();
File share4Dir = myShareDir4CPR.getFile();
ZipFile zipFile = new ZipFile("myTempFile.zip");
zipFile.addFolder(share1Dir);
zipFile.addFolder(share2Dir);
zipFile.addFolder(share3Dir);
zipFile.addFolder(share4Dir);
byte[] binaryData = IOUtils.toByteArray(new FileInputStream(zipFile.getFile()));
headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=output_file.zip;");
result = new ResponseEntity<byte[]>(binaryData, headers, HttpStatus.OK);
} catch (IOException e) {
// TODO Auto-generated catch block
throw new CommonException(e.getMessage());
}
return result;
}
}
Но я не хочу оставлять файл на сервере.
Я сделал следующее:
File createTempFile = File.createTempFile("test", ".zip");
ZipFile zipFile = new ZipFile(createTempFile);
Однако возникает ошибка:
Zip file size less than minimum expected zip file size. Probably not a zip file or a corrupted zip file