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

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

问题描述:

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

I want to download an image and store it in specific folder in local storage.

我正在使用它下载图像:

I am using this to download image:

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

创建FileService接口

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

in your Shared Code, create a new Interface, for instance, called IFileService.cs

 public interface IFileService
 {
      void SavePicture(string name, Stream data, string location="temp");
 }

实施Android

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

In your android project, create a new class called "Fileservice.cs".

确保它源自之前创建的接口,并使用依赖项信息对其进行修饰:

Make sure it derives from your interface created before and decorate it with the dependency information:

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

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

Implementation iOS The implementation for iOS is basically the same:

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

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

In order to save your file, in your shared code, you call

DependencyService.Get<IFileService>().SavePicture("ImageName.jpg", imageData, "imagesFolder");

应该很好.