preamble
In the work we often appear to have more than one file, in order to save resources will be more than one file together for compression; in order to allow you to further understand my first springboot processing methods are summarized below, there is less than please criticize and correct!
I. Documentation preparation:
https:///crmebimage/public/product/2024/11/12/ https:///crmebimage/public/product/2024/11/13/ https:///crmebimage/public/product/2024/11/13/
II. Processing steps:
1. Create a springboot web project This step is omitted here .....
2. Required methods and class writing
(1) Business Methods-TestService
public interface TestService { void compressFiles(List<String> fileUrls, HttpServletResponse response); }
(2) Business method implementation class-TestServiceImpl
@Service @Slf4j public class TestServiceImpl implements TestService { @Override public void compressFiles(List<String> fileUrls, HttpServletResponse response) { try (ZipOutputStream zipOut = new ZipOutputStream(())) { for (String fileUrl : fileUrls) { // 1. Download the file from the network and write it to ZIP. try { URL url = new URL(fileUrl); HttpURLConnection connection = (HttpURLConnection) (); ("GET"); (); // 2. Check the response code if (() != HttpURLConnection.HTTP_OK) { throw new IOException("Failed to download file: " + fileUrl); } // 3. Extract file names from URLs String pathStr = (('/') + 1); // 4. Create ZIP entry ZipEntry zipEntry = new ZipEntry(pathStr); (zipEntry); // 5. Read the input stream of the file try (InputStream inputStream = new BufferedInputStream(())) { byte[] buffer = new byte[1024]; int length; while ((length = (buffer)) >= 0) { (buffer, 0, length); } } (); } catch (IOException e) { ("Error processing file URL: " + fileUrl, e); throw new RuntimeException(e); } }
// 6. Response message setting processing ("application/octet-stream"); ("Content-Disposition", "attachment;filename="); (); } catch (IOException e) { ("Error compressing files", e); throw new RuntimeException(e); } } }
(3) Controller class writing-TestController
/** * @Project: * @Description: * @author: songwp * @Date: 2024/11/13 14:50 **/ @RequestMapping("test") @RestController @Slf4j public class TestController { @Autowired private TestService testService; /** * :: Document compression * *@param fileUrls A list of file URLs to compress. *fileUrls@param response Response object */ @GetMapping("/fileToZip") public void zip(@RequestParam("fileUrls") List<String> fileUrls, HttpServletResponse response) { (fileUrls, response); } }
III. Method invocation display
(1) Storage on desktop
(2) Unzip the file