如何使用Xamarin-Forms下载图像并将其保存在本地存储中.

Par*_*dra 4 c# xamarin.forms

我想下载一个图像并将其存储在本地存储中的特定文件夹中.

我用这个来下载图片:

var imageData = await AzureStorage.GetFileAsync(ContainerType.Image, uploadedFilename);
var img = ImageSource.FromStream(() => new MemoryStream(imageData));
Run Code Online (Sandbox Code Playgroud)

Mar*_*hel 12

创建FileService接口

在您的共享代码中,创建一个新的接口,例如,名为IFileService.cs

 public interface IFileService
 {
      void SavePicture(string name, Stream data, string location="temp");
 }
Run Code Online (Sandbox Code Playgroud)

实施Android

在你的android项目中,创建一个名为"Fileservice.cs"的新类.

确保它派生自之前创建的界面,并使用依赖关系信息进行装饰:

[assembly: Dependency(typeof(FileService))]
namespace MyApp.Droid
{
    public class FileService : IFileService
    {
        public void SavePicture(string name, Stream data, string location = "temp")
        {
            var documentsPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
            documentsPath = Path.Combine(documentsPath, "Orders", location);
            Directory.CreateDirectory(documentsPath);

            string filePath = Path.Combine(documentsPath, name);

            byte[] bArray = new byte[data.Length];
            using (FileStream fs = new FileStream(filePath , FileMode.OpenOrCreate))
            {
                using (data)
                {
                    data.Read(bArray, 0, (int)data.Length);
                }
                int length = bArray.Length;
                fs.Write(bArray, 0, length);
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

实现iOS iOS 的实现基本相同:

[assembly: Dependency(typeof(FileService))]
namespace MyApp.iOS
{
    public class FileService: IFileService
    {
        public void SavePicture(string name, Stream data, string location = "temp")
        {
            var documentsPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
            documentsPath = Path.Combine(documentsPath, "Orders", location);
            Directory.CreateDirectory(documentsPath);

            string filePath = Path.Combine(documentsPath, name);

            byte[] bArray = new byte[data.Length];
            using (FileStream fs = new FileStream(filePath , FileMode.OpenOrCreate))
            {
                using (data)
                {
                    data.Read(bArray, 0, (int)data.Length);
                }
                int length = bArray.Length;
                fs.Write(bArray, 0, length);
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

要保存文件,请在共享代码中调用

DependencyService.Get<IFileService>().SavePicture("ImageName.jpg", imageData, "imagesFolder");
Run Code Online (Sandbox Code Playgroud)

应该很高兴去.

  • 我正在尝试编辑awnser,但不能仅编辑1个字符,在共享代码中,您在DependencyService上获得了Interface,而不是项目实现类DependencyService.Get &lt;IFileService&gt;()。SavePicture(“ ImageName.jpg “,imageData,” imagesFolder“); (2认同)
  • 它应该自动创建一个名为“temp”的文件夹还是将图像保存在哪里?我运行了代码并进行了编译,但找不到我保存的图像 (2认同)