【问题标题】:Java Azure Function - upload file in BLOB ContainerJava Azure 函数 - 在 BLOB 容器中上传文件
【发布时间】:2020-07-08 10:23:06
【问题描述】:

我正在尝试用 Java 制作一个 Azure 函数。我需要制作一个 excel 文件并将其上传到 BLOB 容器中。 当我构建项目并开始测试时,它可以正常工作并将文件上传到容器中,而当我调试项目或将其部署在 Azure 上并通过 Internet 运行它(调用服务)时,它不会不要上传它。当它尝试上传文件时它会阻塞。 你能帮我吗?几天以来我一直在处理这个问题。

谢谢。

我附上上传文件的方法:

@FunctionName("FunctionTest")
public HttpResponseMessage run(
        @HttpTrigger(
            name = "req",
            methods = {HttpMethod.GET, HttpMethod.POST},
            authLevel = AuthorizationLevel.ANONYMOUS)
            HttpRequestMessage<Optional<String>> request,
        final ExecutionContext context) {
    context.getLogger().info("Java HTTP trigger processed a request.");

    final String queryAccountName = request.getQueryParameters().get("AccountName");
    String accountName = request.getBody().orElse(queryAccountName);
    final String queryAccountKey = request.getQueryParameters().get("AccountKey");
    String accountKey = request.getBody().orElse(queryAccountKey);

    context.getLogger().info("Azure Blob storage v12 - Java quickstart sample\n");

    // Retrieve the connection string for use with the application. The storage
    // connection string is stored in an environment variable on the machine
    // running the application called AZURE_STORAGE_CONNECTION_STRING. If the environment variable
    // is created after the application is launched in a console or with
    // Visual Studio, the shell or application needs to be closed and reloaded
    // to take the environment variable into account.
    // String connectStr = System.getenv("AZURE_STORAGE_CONNECTION_STRING");

    //String connectStr = "DefaultEndpointsProtocol=https;AccountName="+accountName+";AccountKey="+accountKey+";EndpointSuffix=core.windows.net";
    // Create a BlobServiceClient object which will be used to create a container client
    //BlobServiceClient blobServiceClient = new BlobServiceClientBuilder().connectionString(connectStr).buildClient();
    StorageSharedKeyCredential credential = new StorageSharedKeyCredential(accountName, accountKey);
    String endpoint = String.format(Locale.ROOT, "https://%s.blob.core.windows.net", accountName);
    BlobServiceClient blobServiceClient = new BlobServiceClientBuilder().endpoint(endpoint).credential(credential).buildClient();

    //Create a unique name for the container
    String containerName = "container-name";

    // Create the container and return a container client object
    //BlobContainerClient containerClient = blobServiceClient.createBlobContainer(containerName);
    BlobContainerClient containerClient = blobServiceClient.getBlobContainerClient(containerName);

    // Create a local file in the ./data/ directory for uploading and downloading
    /*String pathFile = "./data/";
    String fileName = "quickstart" + java.util.UUID.randomUUID() + ".txt";
    File localFile = new File(pathFile + fileName);

    // Write text to the file
    FileWriter writer;
    try {
        writer = new FileWriter(pathFile + fileName, true);
        writer.write("Hello, World!");
        writer.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }*/

    // Get a reference to a blob
    // Upload the blob
    String pathFile = System.getenv("TEMP") + "\\";
    String fileName = creaReport(context)+".xlsx"; // creating file Excel - IT DOESN'T EVEN WORK WITH TXT FILE
    BlobClient blobClient = containerClient.getBlobClient(fileName);

    System.out.println("\nUploading to Blob storage as blob:\n\t" + blobClient.getBlobUrl());

    blobClient.uploadFromFile(pathFile + fileName, true);  // IT BLOCKS HERE

    System.out.println("\nListing blobs...");

    // List the blob(s) in the container.
    for (BlobItem blobItem : containerClient.listBlobs()) {
        System.out.println("\t" + blobItem.getName());
    }

    // Download the blob to a local file
    // Append the string "DOWNLOAD" before the .txt extension so that you can see both files.
    //String downloadFileName = fileName.replace(".txt", "DOWNLOAD.txt");
    String downloadFileName = fileName.replace(".xlsx", "DOWNLOAD.xlsx");
    File downloadedFile = new File(pathFile + downloadFileName);

    System.out.println("\nDownloading blob to\n\t " + pathFile + downloadFileName);

    blobClient.downloadToFile(pathFile + downloadFileName, true);

    // Clean up
    System.out.println("\nPress the Enter key to begin clean up");
    System.console().readLine();

    /*System.out.println("Deleting blob container...");
    containerClient.delete();*/

    System.out.println("Deleting the local source and downloaded files...");
    localFile.delete();
    downloadedFile.delete();

    System.out.println("Done");

    return request.createResponseBuilder(HttpStatus.OK).body("Blob uploaded").build();

}

【问题讨论】:

  • 您从哪里获得创建 xlsx 文件的内容...我建议您使用基于 Stream 的方法而不是将文件保存到磁盘...您能否提供更多信息跨度>
  • 您好 Fabio,请问您的问题是否已解决?如果还有问题,请告诉我

标签: java azure azure-functions azure-blob-storage


【解决方案1】:

对于这个问题,我自己测试了一下,总结如下:

此问题的原因是local/temp 中的文件未在站点实例之间共享。可以参考这个page。

所以我遇到了和你一样的问题,我将我的 java 函数部署到 azure 并手动在 local/temp 路径下添加一个文件。然后运行该函数,它无法访问文件的数据。

之后,我编辑我的功能代码。在我的函数中通过下面的代码创建一个txt文件:

String filePath="d:\\local\\Temp\\test1.txt";
File file = new File(filePath);

try {
    FileWriter writer = new FileWriter(file);
    writer.write("Test data");
    writer.close();
} catch (IOException e1) {
    context.getLogger().info(e1.getMessage());
    e1.printStackTrace();
}

然后通过下面的代码在同一个函数中读取文件:

InputStream is = null;
int i;
char c;
try {
    is = new FileInputStream(filePath);
    while ((i = is.read()) != -1) {
        c = (char) i;
        context.getLogger().info("===inputstream==" + c);
    }
} catch (Exception e) {
    context.getLogger().info("===try catch error");
    e.printStackTrace();
} finally {
    if (is != null) {
        try {
            is.close();
        } catch (IOException e) {
            context.getLogger().info("===finally error");
            e.printStackTrace();
        }
    }  
}

将代码部署到 azure,函数应用在消费计划中运行(所以如果我只运行一次,它将只使用一个实例)。运行它,我读取文件成功的数据。

根据上面的测试,我建议你不要在local/temp创建文件。你最好在d:\home\site\wwwroot下创建文件,你可以在wwwroot下创建一个文件夹,并在该文件夹下创建文件。我测试它工作正常。

希望对你有帮助~

【讨论】:

    猜你喜欢
    • 2020-01-09
    • 1970-01-01
    • 2011-02-06
    • 2020-01-31
    • 2022-01-12
    • 2021-07-16
    • 1970-01-01
    • 2021-09-11
    • 1970-01-01
    相关资源
    最近更新 更多