1 Aralık 2020 Salı

SpringContext Resource Arayüzü - Dosya İndirme

Giriş
Bazı gerçekleştiren sınıflar şöyle

exists metodu

Örnek
Şöyle yaparız
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;

private final Path root = Paths.get("uploads");

@Override
public Resource load(String filename) {
  try {
    Path file = root.resolve(filename);
    Resource resource = new UrlResource(file.toUri());

    if (resource.exists() || resource.isReadable()) {
      return resource;
    } else {
      throw new RuntimeException("Could not read the file!");
    }
  } catch (MalformedURLException e) {
    throw new RuntimeException("Error: " + e.getMessage());
  }
}
isReadable metodu
Örnek
Şöyle yaparız
//This method will serve the files to download
override fun download(filename:String):Result<Resource> =
  runCatching {
    log.debug { "Downloading file $filename from ${uploadsFolderPath.fileName} folder"}
    val file: Path = uploadsFolderPath.resolve(filename)

    val resource: Resource = UrlResource(file.toUri())
    if (resource.exists() || resource.isReadable)
      resource
    else throw FileNotFoundException("The file does not exist or is not readable!")
  }.onFailure {
    log.warn { "Error downloading file $filename reason: ${it.javaClass}" }
}
readableChannel metodu
Şöyle yaparız
public void put(String name, MultipartFile file) throws IOException {
  var length = (int) file.getSize();
  var byteBuffer = ByteBuffer.allocateDirect(length);
  try (var channel = file.getResource().readableChannel()) {
    IOUtils.readFully(channel, byteBuffer);
  }
  byteBuffer.position(0);
  ...
}





Hiç yorum yok:

Yorum Gönder