race155
race155

Reputation: 23

Saving uploaded file from user with bot framework c#

I am currently trying to allow a user to upload a file to the bot during a dialog flow. From there the bot will take the file and upload it to blob storage. When the file comes in the content property is null, however the content url, name, and type all have the correct values.

    public virtual async Task StackTraceGathered(IDialogContext context, IAwaitable<IMessageActivity> argument)
    {
        var message = await argument;
        FileName = message.Attachments[0].Name;
        HttpPostedFileBase file = (HttpPostedFileBase)message.Attachments[0].Content;

        string filePath = HttpContext.Current.Server.MapPath("~/Files/" + file.FileName);
        file.SaveAs(filePath);

        if (message.Attachments != null && message.Attachments.Any())
        {
            var attachment = message.Attachments.First();
            using (HttpClient httpClient = new HttpClient())
            {
                // Skype & MS Teams attachment URLs are secured by a JwtToken, so we need to pass the token from our bot.
                if ((message.ChannelId.Equals("skype", StringComparison.InvariantCultureIgnoreCase) || message.ChannelId.Equals("msteams", StringComparison.InvariantCultureIgnoreCase))
                    && new Uri(attachment.ContentUrl).Host.EndsWith("skype.com"))
                {
                    var token = await new MicrosoftAppCredentials().GetTokenAsync();
                    httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
                }

                var responseMessage = await httpClient.GetAsync(attachment.ContentUrl);

                var contentLenghtBytes = responseMessage.Content.Headers.ContentLength;

                await context.PostAsync($"Attachment of {attachment.ContentType} type and size of {contentLenghtBytes} bytes received.");
            }
        }
        else
        {
            await context.PostAsync("Hi there! I'm a bot created to show you how I can receive message attachments, but no attachment was sent to me. Please, try again sending a new message including an attachment.");
        }
        PromptDialog.Text(context, ProblemStartDuration, "How long has this been an issue? (Provide answer in days, if issue has been occurring for less than one day put 1).");

        context.Wait(this.StackTraceGathered);
    }

Upvotes: 0

Views: 1624

Answers (1)

Ezequiel Jadib
Ezequiel Jadib

Reputation: 14787

I don't see the issue, but I guess you are expecting the Content property to have something. It won't but you just need the Url. Two alternatives:

  • Download the attachment in the bot (as the code you are using in the question) and upload to blob storage
  • Try to upload the attachment directly from the Url using something like StartCopyFromBlob (check this)

Upvotes: 1

Related Questions