【发布时间】:2019-03-15 15:31:07
【问题描述】:
我在主 bot 类中的 OnTurnAsync() 中有此代码,可让用户上传图像并将其保存在本地并且工作正常。
但是,如果我想在 MainDialog 类等不同的类中执行此操作,我该怎么做呢?
更新:我设法通过下面的代码来做到这一点。但它接受一切,我怎么能做一个只接受图像的验证?
更新:在下面回答。
public class MainDialog : ComponentDialog
{
private const string InitialId = "mainDialog";
private const string TEXTPROMPT = "textPrompt";
private const string ATTACHPROMPT = "attachPrompt";
public MainDialog(string dialogId)
: base(dialogId)
{
WaterfallStep[] waterfallSteps = new WaterfallStep[]
{
FirstStepAsync,
SecondStepAsync,
};
AddDialog(new WaterfallDialog(InitialId, waterfallSteps));
AddDialog(new AttachmentPrompt(ATTACHPROMPT));
}
private static async Task<DialogTurnResult> FirstStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken = default(CancellationToken))
{
return await stepContext.PromptAsync(
ATTACHPROMPT,
new PromptOptions
{
Prompt = MessageFactory.Text($"upload photo."),
RetryPrompt = MessageFactory.Text($"upload photo pls."),
});
}
private static async Task<DialogTurnResult> SecondStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken = default(CancellationToken))
{
var activity = stepContext.Context.Activity;
if (activity.Attachments != null && activity.Attachments.Any())
{
foreach (var file in stepContext.Context.Activity.Attachments)
{
var remoteFileUrl = file.ContentUrl;
var localFileName = Path.Combine(Path.GetTempPath(), file.Name);
using (var webClient = new WebClient())
{
webClient.DownloadFile(remoteFileUrl, localFileName);
}
await stepContext.Context.SendActivityAsync($"Attachment {stepContext.Context.Activity.Attachments[0].Name} has been received and saved to {localFileName}.");
}
}
return await stepContext.EndDialogAsync();
}
用这段代码设法做到了。
var activity = stepContext.Context.Activity;
if (activity.Attachments != null && activity.Attachments.Any())
{
foreach (var file in stepContext.Context.Activity.Attachments)
{
if (file.ContentType.EndsWith("/jpg") || file.ContentType.EndsWith("/png") || file.ContentType.EndsWith("/bmp") || file.ContentType.EndsWith("/jpe"))
{
var remoteFileUrl = file.ContentUrl;
var localFileName = Path.Combine(Path.GetTempPath(), file.Name);
using (var webClient = new WebClient())
{
webClient.DownloadFile(remoteFileUrl, localFileName);
}
await stepContext.Context.SendActivityAsync($"Attachment {stepContext.Context.Activity.Attachments[0].Name} has been received and saved to {localFileName}.");
return await stepContext.NextAsync();
}
else
{
await stepContext.Context.SendActivityAsync($"Attachment {file.Name} is not an image, it is {file.ContentType}.");
// restart the dialog from top
return await stepContext.ReplaceDialogAsync(InitialId);
}
}
}
【问题讨论】:
-
你只需要检查附件的
contentType
标签: c# botframework messenger