vue+springboot文件夹压缩下载
时间: 2023-09-20 10:05:00 浏览: 53
您可以使用以下步骤将文件夹压缩并提供下载:
1. 在后端(Spring Boot)中,使用`java.util.zip`库将文件夹压缩为ZIP文件。您可以使用以下代码示例:
```java
public void zipFolder(String sourceFolderPath, String zipFilePath) throws Exception {
FileOutputStream fos = new FileOutputStream(zipFilePath);
ZipOutputStream zipOut = new ZipOutputStream(fos);
File fileToZip = new File(sourceFolderPath);
zipFile(fileToZip, fileToZip.getName(), zipOut);
zipOut.close();
fos.close();
}
private void zipFile(File fileToZip, String fileName, ZipOutputStream zipOut) throws Exception {
if (fileToZip.isHidden()) {
return;
}
if (fileToZip.isDirectory()) {
if (fileName.endsWith("/")) {
zipOut.putNextEntry(new ZipEntry(fileName));
zipOut.closeEntry();
} else {
zipOut.putNextEntry(new ZipEntry(fileName + "/"));
zipOut.closeEntry();
}
File[] children = fileToZip.listFiles();
for (File childFile : children) {
zipFile(childFile, fileName + "/" + childFile.getName(), zipOut);
}
return;
}
FileInputStream fis = new FileInputStream(fileToZip);
ZipEntry zipEntry = new ZipEntry(fileName);
zipOut.putNextEntry(zipEntry);
byte[] bytes = new byte[1024];
int length;
while ((length = fis.read(bytes)) >= 0) {
zipOut.write(bytes, 0, length);
}
fis.close();
}
```
2. 在前端(Vue.js)中,使用axios库将ZIP文件下载到客户端。您可以使用以下代码示例:
```javascript
downloadZip() {
axios({
url: "/api/zip",
method: "GET",
responseType: "blob"
}).then(response => {
const url = window.URL.createObjectURL(new Blob([response.data]));
const link = document.createElement("a");
link.href = url;
link.setAttribute("download", "folder.zip");
document.body.appendChild(link);
link.click();
});
}
```
3. 在后端中,创建一个REST API端点,以便Vue.js应用程序可以下载ZIP文件。您可以使用以下代码示例:
```java
@RestController
@RequestMapping("/api")
public class ZipController {
@GetMapping(value = "/zip", produces = "application/zip")
public void downloadZip(HttpServletResponse response) throws Exception {
String sourceFolderPath = "path/to/folder";
String zipFilePath = "path/to/folder.zip";
zipFolder(sourceFolderPath, zipFilePath);
File file = new File(zipFilePath);
InputStream inputStream = new FileInputStream(file);
response.setHeader("Content-Disposition", "attachment; filename=\"folder.zip\"");
IOUtils.copy(inputStream, response.getOutputStream());
response.flushBuffer();
}
}
```
注意:您需要将“path/to/folder”替换为实际的文件夹路径。