Spring Boot - 从Azure Blob Storage上传或下载时的问题

2 人关注

我们有一个网络应用程序,正在用 Angular 2+ ,它使用后台网络服务消耗数据,这些服务正在用 Spring boot

后台使用Azure Blob存储来存储图片、视频、PDF等。

目前的流程是,网络应用(客户端)向服务器发送Multipart文件,后端会将 org.springframework.web.multipart.MultipartFile 转为 java.io.File ,如下所示

public static File convert(MultipartFile file) throws IOException {
  File convFile = new File(file.getOriginalFilename());
  convFile.createNewFile();
  FileOutputStream fos = new FileOutputStream(convFile);
  fos.write(file.getBytes());
  fos.close();
  return convFile;

将文件上传至Azure Blob

 ContainerURL  containerURL = serviceURL.createContainerURL("images");
  BlockBlobURL blob = final BlockBlobURL blobURL = 
  containerURL.createBlockBlobURL("nature.png");
  Path sourceFile = convert().toPath();
  AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(sourceFile.toPath());
                // Uploading a file to the blobURL using the high-level methods available in TransferManager class
                // Alternatively call the PutBlob/PutBlock low-level methods from BlockBlobURL type
                TransferManager.uploadFileToBlockBlob(fileChannel, blob, 8*1024*1024, null, null)
                .subscribe(response-> {
                    System.out.println("Completed upload request.");
                    System.out.println(response.response().statusCode());

使用BlockBlobURL 下载文件,并向客户端发送路径。

static void getBlob(BlockBlobURL blobURL, File sourceFile) throws IOException {
        AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(sourceFile.toPath(), StandardOpenOption.CREATE, StandardOpenOption.WRITE);
        TransferManager.downloadBlobToFile(fileChannel, blobURL, null, null)
        .subscribe(response-> {
            System.out.println("Completed download request.");
            System.out.println("The blob was downloaded to " + sourceFile.getAbsolutePath());