没有机制可以检索文件在磁盘上的路径或用户上传它的本地路径(这被视为安全风险:
如何使用jav获取更改文件输入类型时所选文件的完整路径)。
因为机器人连接到仿真器,所以
ContentUrl属性是
http://localhost:56057/v3/attachments/guid/views/original。该路径是Bot Framework Channel特定的。您的本地仿真器服务器托管在端口56057上。如评论中所述,您需要下载文件并将其保存在某个位置。
此示例演示了如何检索文件的字节:
core-ReceiveAttachment。
粗略修改以保存本地文件夹中的多个文件:(在生产环境中,没有其他保障措施,这不是一个好主意。最好使用
Microsoft.WindowsAzure.Storage或类似的东西将字节上传到blob存储中。)
if (message.Attachments != null && message.Attachments.Any())
{
using (HttpClient httpClient = new HttpClient())
{
if ((message.ChannelId.Equals(ChannelIds.Skype, StringComparison.InvariantCultureIgnoreCase)
|| message.ChannelId.Equals(ChannelIds.Msteams, StringComparison.InvariantCultureIgnoreCase)))
{
var token = await new MicrosoftAppCredentials().GetTokenAsync();
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
}
foreach (Attachment attachment in message.Attachments)
{
using (var responseMessage = await httpClient.GetAsync(attachment.ContentUrl))
{
using (var fileStream = await responseMessage.Content.ReadAsStreamAsync())
{
string path = Path.Combine(System.Web.HttpContext.Current.Request.MapPath("~\\Content\\Files"), attachment.Name);
using (FileStream file = new FileStream(path, FileMode.Create, FileAccess.Write))
{
await fileStream.CopyToAsync(file);
file.Close();
}
}
var contentLenghtBytes = responseMessage.Content.Headers.ContentLength;
await context.PostAsync($"Attachment of {attachment.ContentType} type and size of {contentLenghtBytes} bytes received.");
}
}
}
}
这个BotBuilder-v4的示例展示了另一种方法:
15.handling-attachments/AttachmentsBot.cs#L204。
private static void HandleIncomingAttachment(IMessageActivity activity, IMessageActivity reply)
{
foreach (var file in activity.Attachments)
{
var remoteFileUrl = file.ContentUrl;
var localFileName = Path.Combine(Path.GetTempPath(), file.Name);
using (var webClient = new WebClient())
{
webClient.DownloadFile(remoteFileUrl, localFileName);
}
reply.Text = $"Attachment \"{activity.Attachments[0].Name}\"" +
$" has been received and saved to \"{localFileName}\"";
}
}