【发布时间】:2020-05-12 14:10:08
【问题描述】:
我正在开发一个 Xamarin 应用程序,它从数据库中检索信息,拍摄/选择照片并将它们上传到远程服务器,从远程服务器显示这些图像,用户可以通过点击并按下按钮来删除它们。最后一步是将存储在服务器中的图像下载到本地设备库。
这是我当前的按钮点击事件:
private void button_download_image_Clicked(object sender, EventArgs e)
{
Uri image_url_format = new Uri(image_url);
WebClient webClient = new WebClient();
try
{
webClient.DownloadDataAsync(image_url_format);
webClient.DownloadDataCompleted += webClient_DownloadDataCompleted;
}
catch (Exception ex)
{
DisplayAlert("Error", ex.ToString(), "OK");
}
}
webClient_DownloadDataCompleted 方法下方:
private void webClient_DownloadDataCompleted(object sender, DownloadDataCompletedEventArgs e)
{
try
{
Uri image_url_format = new Uri(image_url);
byte[] bytes_image = e.Result;
Stream image_stream = new MemoryStream(bytes_image);
string dest_folder= Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDownloads).ToString();
string file_name= Path.GetFileName(image_url_format.LocalPath);
string dest_path= Path.Combine(dest_folder, file_name);
using (var fileStream = new FileStream(dest_path, FileMode.Create, FileAccess.Write))
{
image_stream.CopyTo(fileStream);
}
DisplayAlert("Alert", "Download completed!", "OK");
}
catch (Exception ex)
{
DisplayAlert("Error", ex.ToString(), "OK");
}
}
但它不起作用,没有发现错误,我收到警告,警告我下载已完成。我还授予了 internet、write_external_storage 和 read_external_storage 的权限。
另一件事是图像在一段时间后出现在下载相册下的图库中,这是正确的。
对这种行为有任何想法吗?
编辑
在我的新按钮下载事件下方:
private void button_download_image_Clicked(object sender, EventArgs e)
{
Uri image_url_format = new Uri(image_url);
WebClient webClient = new WebClient();
try
{
byte[] bytes_image = webClient.DownloadData(image_url_format);
Stream image_stream = new MemoryStream(bytes_image);
string dest_folder = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDownloads).ToString();
string file_name = Path.GetFileName(image_url_format.LocalPath);
string dest_path = Path.Combine(dest_folder, file_name);
using (var fileStream = new FileStream(dest_path, FileMode.Create, FileAccess.Write))
{
image_stream.CopyTo(fileStream);
}
}
catch (Exception ex)
{
DisplayAlert("Error", ex.ToString(), "OK");
}
DisplayAlert("Alert", "File scaricato con successo", "OK");
}
【问题讨论】:
-
由于您的图片出现在图库中,就好像它实际上已经被下载了一样。请更彻底地描述预期的行为是什么,b/c 从你写的内容中并不清楚。
-
@PaulKertscher 预期的行为是:按下下载按钮 -> 图像将保存在设备的 Downloads 文件夹中。一切顺利,但图像没有出现在文件夹中,也没有出现在图库中。
-
您是否使用文件资源管理器检查它确实不存在。可能是由于某种原因,图库无法正确刷新。
-
@PaulKertscher 是的,我检查了文件资源管理器但没有成功。奇怪的是,当我连接到我家的wifi时,我可以在图库中看到图像,这只是巧合吗?
标签: c# xamarin xamarin.forms download xamarin.android