简体   繁体   中英

Upload a pdf file to azure blob using azure function

I am trying to upload a PDF file from postman and trigger the azure function to upload the PDF file into azure blob storage. But when i try to open the PDF file it is always empty.

I tried to convert the file into memory stream and upload it into azure blob. The file gets uploaded but when i try to open the file it will be blank.

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");
        }

I want to open the PDF file as it is from the blob. I see that i am able to upload text file and when i download i can see the content but when i upload pdf file i dont see the content

Calling .ReadAsStringAsync on a binary document wont work - you have to call ReadAsByteArrayAsync or ReadAsStreamAsync .

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);

It's really simple to do something like that. Everything relative to bindings should be declared in the function parameters so, having this in mind, you have to declare your blob stream as a parameter. Check this as an example:


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

Please, note the second parameter called blob is declared as a Stream to be able to save the content read from the input. The second point is the attribute decorating the parameter, Blob allows to define several aspects of the new blob file that will be uploaded in our Azure Storage service. As you can see, the container is called azurefunctions and the file will be called test.pdf .

In order to save the content you can use the following code:


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

Hope this can be helpful for your question.

These are useful links to check and test your code:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM