使用azure函数将pdf文件上传到azure blob

时间:2019-06-18 12:12:12

标签: c# asp.net azure azure-functions

我正在尝试从邮递员上载PDF文件,并触发azure函数将PDF文件上载到azure blob存储中。但是当我尝试打开PDF文件时,它始终为空。

我试图将文件转换为内存流,并将其上传到天蓝色的blob。该文件已上传,但是当我尝试打开文件时,它将为空白。

public static async Task<HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)]HttpRequestMessage req, TraceWriter log)
        {
            log.Info(req.Content.ToString());
            string Message = "";
            log.Info("Test storage conn string" + req.Content.Headers.ContentDisposition.ToString());
            string contentType = req.Content.Headers?.ContentType?.MediaType;
            log.Info("contentType : " + req.Content.IsMimeMultipartContent());
            string name = Guid.NewGuid().ToString("n");
            log.Info("Name" + name);
            string body;

            body = await req.Content.ReadAsStringAsync();

            log.Info("body" + body.Substring(body.IndexOf("filename=\""),body.IndexOf("pdf")- body.IndexOf("filename=\"")));
            //Upload a file to Azure blob
            string storageConnectionString = "xxxx";

            //DirectoryInfo directoryInfo = new DirectoryInfo("D:\\Upload_Files");

           // var files = directoryInfo.EnumerateFiles();

            // Retrieve storage account from connection string.
            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(storageConnectionString);

            // Create the blob client.
            CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();

            // Retrieve reference to a previously created container.
            CloudBlobContainer container = blobClient.GetContainerReference("docstorage");

            //foreach (FileInfo inputFile in files)
            //{

                CloudBlockBlob blockBlob = container.GetBlockBlobReference("Test\\" + name+".pdf");//write name here
            //blockBlob.Properties.ContentType = "application/pdf";
                //blockBlob.UploadFromFile(inputFile.FullName);
            using (Stream stream = new MemoryStream(Encoding.UTF8.GetBytes(body)))
            {
                log.Info("streaming : ");
                await blockBlob.UploadFromStreamAsync(stream);
            }
            //}


            return Message == null
                ? req.CreateResponse(HttpStatusCode.BadRequest, "Error")
                : req.CreateResponse(HttpStatusCode.OK, "Doc Uploaded Successfully");
        }

我想打开Blob中的PDF文件。我看到我能够上传文本文件,下载时可以看到内容,但是当我上传pdf文件时看不到内容

2 个答案:

答案 0 :(得分:1)

在二进制文档上调用.ReadAsStringAsync无效-您必须调用ReadAsByteArrayAsyncReadAsStreamAsync

var body = await req.Content.ReadAsByteArrayAsync();
...
using (Stream stream = new MemoryStream(body))
{
    await blockBlob.UploadFromStreamAsync(stream);
}

OR

var body2 = await req.Content.ReadAsStreamAsync();
body.Position = 0;
...
await blockBlob.UploadFromStreamAsync(body);

答案 1 :(得分:0)

做这样的事情真的很简单。与绑定有关的所有内容都应在函数参数中声明,因此,牢记这一点,您必须将blob流声明为参数。以此为例:


    public static async Task<string> Run(
        [HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequest req,
        [Blob("azurefunctions/test.pdf", FileAccess.Write)] Stream blob,
        ILogger log)

请注意,第二个参数 blob 被声明为 Stream ,以便能够保存从输入中读取的内容。第二点是装饰参数的属性, Blob 可以定义将要在我们的 Azure Storage 服务中上传的新blob文件的多个方面。如您所见,该容器称为 azurefunctions ,文件将称为 test.pdf

为了保存内容,您可以使用以下代码:


    byte[] content = new byte[req.Body.Length];
    await req.Body.ReadAsync(content, 0, (int)req.Body.Length);
    await blob.WriteAsync(content, 0, content.Length);

希望这对您的问题有所帮助。

这些是检查和测试代码的有用链接: