简体   繁体   English

如何从 url 下载照片并保存在 Xamarin

[英]How to download a photo from url and save in Xamarin

I need Xamarin to call a GET API that downloads a photo from a url and save it in the phone.我需要 Xamarin 来调用 GET API 从 url 下载照片并将其保存在手机中。 When xamarin calls the API, it will download a image from a url and then return it as response to xamarin, after this I will save the photo in the phone. When xamarin calls the API, it will download a image from a url and then return it as response to xamarin, after this I will save the photo in the phone.

The API is a C# 4.0 MVC. API 是 C# 4.0 MVC。 I created a Get API that downloads the image successfully and returns it as FileStreamResult.我创建了一个 Get API,它成功下载了图像并将其作为 FileStreamResult 返回。

The API downloads the image from a url and return it API 从 url 下载图像并返回

public FileStreamResult DownloadFoto()
        {

            Stream rtn = null;
            string aURL = "https://image.shutterstock.com/image-vector/sample-stamp-grunge-texture-vector-260nw-1389188336.jpg";
            HttpWebRequest aRequest = (HttpWebRequest)WebRequest.Create(aURL);
            HttpWebResponse aResponse = (HttpWebResponse)aRequest.GetResponse();
            rtn = aResponse.GetResponseStream();
            return File(rtn, "image/jpeg", foto);
        }

Xamarin Forms HttpConnectionis an instance of HttpClient. Xamarin Forms HttpConnection是HttpClient的一个实例。

var Response = await Application.HttpConnection.GetAsync("DownloadFoto");
                        DependencyService.Get<IFileService>().SavePicture("ImageName.jpg", Response.Content.ReadAsStreamAsync().Result, "imagesFolder");

Xamarin Android Xamarin Android

[assembly: Dependency(typeof(FileService))]
namespace Diario.Droid
{
    public class FileService : IFileService
    {
        public void SavePicture(string name, Stream data, string location = "temp")
        {
            var documentsPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
            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);
            }
        }
    }
}

I don't get any error, it looks to be saving the image, but when I look for it in File Management I don't find the image there.我没有收到任何错误,它看起来正在保存图像,但是当我在文件管理中查找它时,我在那里找不到图像。

Yeah the directory path your are getting with:是的,您正在使用的目录路径:

var documentsPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);

It is pointing at somewhere in /data/user/ which will be private to the App.它指向/data/user/中的某个位置,该位置对应用程序是私有的。 If you want to make it browse-able using a File Explorer App, you will probably need to save it somewhere in External Storage (public storage).如果您想使用文件资源管理器应用程序使其可浏览,您可能需要将其保存在外部存储(公共存储)中的某个位置。

You can get a path for that with:您可以通过以下方式获得路径:

var externalDir = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDocuments);

If you are targeting Android API 18 and lower, remember to add permissions for that in your AndroidManifest:如果您的目标是 Android API 18 及更低版本,请记住在您的 AndroidManifest 中添加权限:

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" android:maxSdkVersion="18" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" android:maxSdkVersion="18" />

Since some devices on Android can have their External Storage on microSD cards, you will need to check whether you can write to it first:由于 Android 上的某些设备可以将其外部存储放在 microSD 卡上,因此您需要先检查是否可以对其进行写入:

var stateOk = Android.OS.Environment.ExternalStorageState == Android.OS.Environment.MediaMounted;
if (stateOk)
{
    // I can write!
}

From Android API 23 and up, you will need to request permission before being able to read and write to external storage.从 Android API 23 及以上版本开始,您需要先请求权限,然后才能读取和写入外部存储。 You could use this plugin to easily ask for permissions: https://github.com/jamesmontemagno/PermissionsPlugin您可以使用此插件轻松请求权限: https://github.com/jamesmontemagno/PermissionsPlugin

Another couple of things to notice.还有几件事需要注意。 You are using .Result on your ReadAsStreamAsync() call.您在ReadAsStreamAsync()调用中使用.Result Just keep in mind that you will be blocking the thread you are on.请记住,您将阻塞您所在的线程。 I highly suggest you design your methods to be async all the way.我强烈建议您将方法设计为始终异步。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM