如何将文件从 azure 函数应用程序发送到 azure 存储

问题描述

我正在使用 azure 函数应用程序(服务总线),每次在 UI 中上传 excel 文件时都会触发该应用程序。 并且出于任何原因,如果 excel 文件无法上传,则会引发异常消息。 我想将该异常消息存储到文本文件中,并将该文本文件存储到存储帐户中。 请建议我如何将该文件从我的函数应用程序存储到存储帐户中。

异常代码如下:

catch (Exception ex)
        {
            logger.Loginformation($"Exception: {ex.Message},{ex.StackTrace}");
            return "Failure";
        }

解决方法

也许您可以尝试使用此代码:

            catch (Exception ex)
            {
                log.LogInformation($"Exception: {ex.Message},{ex.StackTrace}");

                string connectionString = "";
                BlobServiceClient blobServiceClient = new BlobServiceClient(connectionString);
                string containerName = "";

                // Create a local file in the ./data/ directory for uploading and downloading
                string localPath = "./data/";
                string fileName = "exception" + Guid.NewGuid().ToString() + ".txt";
                string localFilePath = Path.Combine(localPath,fileName);

                // Write text to the file
                await File.WriteAllTextAsync(localFilePath,$"Exception: {ex.Message},{ex.StackTrace}");
                BlobContainerClient containerClient = blobServiceClient.GetBlobContainerClient(containerName);
                // Get a reference to a blob
                BlobClient blobClient = containerClient.GetBlobClient(fileName);

                // Open the file and upload its data
                using FileStream uploadFileStream = File.OpenRead(localFilePath);
                await blobClient.UploadAsync(uploadFileStream,true);
                uploadFileStream.Close();

                return "Failure";
            }

请参阅此official documentation