【问题标题】:Saving uploaded file from user with bot framework c#使用 bot 框架 c# 从用户保存上传的文件
【发布时间】:2017-05-18 05:41:15
【问题描述】:

我目前正在尝试允许用户在对话流期间将文件上传到机器人。机器人将从那里获取文件并将其上传到 blob 存储。当文件进入时,内容属性为空,但是内容 url、名称和类型都具有正确的值。

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

【问题讨论】:

    标签: c# file-upload botframework


    【解决方案1】:

    我没有看到问题,但我猜您希望 Content 属性有一些东西。它不会,但你只需要 URL。两种选择:

    • 在机器人中下载附件(作为您在问题中使用的代码)并上传到 blob 存储
    • 尝试使用 StartCopyFromBlob 之类的方式直接从 URL 上传附件(检查 this

    【讨论】:

    • 我尝试按照其他堆栈溢出的指示直接上传附件。它说远程服务器返回了 404 not found 错误。
    • 如果您在浏览器中导航到 URL 会发生什么?
    • 内容 URL 将允许您下载文件,或者如果它是图像则显示图像。
    • 是的,我预料到了......所以不知道为什么你得到了 404......无论如何,你可以选择选项 #1
    • 您能否解释一下我们将如何上传到 blob 存储?我对如何使用 url 执行此操作有点困惑。我使用文件流阅读器引用的示例,但不包含 uri。
    猜你喜欢
    • 1970-01-01
    • 2013-02-09
    • 1970-01-01
    • 2013-04-27
    • 1970-01-01
    • 1970-01-01
    • 2013-07-20
    • 1970-01-01
    • 2013-11-21
    相关资源
    最近更新 更多