Код: Выделить всё
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.model.ListObjectsV2Result;
import com.amazonaws.services.s3.model.S3Object;
import com.amazonaws.services.s3.model.S3ObjectSummary;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
@RestController
public class DownloadController {
@Autowired
private AmazonS3 s3Client;
private static final String BUCKET_NAME = "fftodcf";
@GetMapping("/conversion/feature-file/{batchId}")
public ResponseEntity downloadFiles(@PathVariable String batchId) {
String keyPrefix = "converted/" + batchId + "/";
try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
ZipOutputStream zipOutputStream = new ZipOutputStream(byteArrayOutputStream)) {
// Get the list of files in the specified S3 folder
ListObjectsV2Result result = s3Client.listObjectsV2(BUCKET_NAME, keyPrefix);
// Loop through all the files and add them to the zip
for (S3ObjectSummary summary : result.getObjectSummaries()) {
try (S3Object s3Object = s3Client.getObject(BUCKET_NAME, summary.getKey())) {
zipOutputStream.putNextEntry(new ZipEntry(summary.getKey().replace(keyPrefix, "")));
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = s3Object.getObjectContent().read(buffer)) != -1) {
zipOutputStream.write(buffer, 0, bytesRead);
}
zipOutputStream.closeEntry();
}
}
// Finish the zip file
zipOutputStream.finish();
// Create a ByteArrayResource from the output stream
ByteArrayResource resource = new ByteArrayResource(byteArrayOutputStream.toByteArray());
// Set headers to download the zip file
HttpHeaders headers = new HttpHeaders();
headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + batchId + "_files.zip");
return ResponseEntity.ok()
.headers(headers)
.contentLength(resource.contentLength())
.body(resource);
} catch (IOException e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
}
}
}
Ошибка сжатых (архивированных) папок
Windows не может открыть папку.
Сжатая (архивированная) папка
0baf1795-9d7d-4001-8765-56725c06ca1e_files.zip' недействителен.
Я ожидал, что будет загружен zip-архив со всеми файлами в нем
я развернул этот код на aws лямбда, но не могу загрузить файлы, всегда получаю неверный zip-файл, и я почти уверен, что в папке есть файлы
Подробнее здесь: https://stackoverflow.com/questions/790 ... ways-getti
Мобильная версия