How to hit an URL to download a file ?

RaylightRaylight Member ✭✭
edited September 2018 in Xamarin.Forms

Hello i'm a beginner in xamarin,

been trying to download a .zip file from an adresse (if i paste the adress to my browser the download start)
Already tried the DownloadManager plugin with the sample they give on there github
var downloadManager = CrossDownloadManager.Current; var file = downloadManager.CreateDownloadFile(url); downloadManager.Start(file);
but its not working for me, i download somekind of .bin.
My question is simple (and i think the answer to) how can i hit this URL within my app to get the file on my phone ?
Thanks for your time and have a good day !

Edit : i'm working on visual studio with latest update and its a .NETstandard project (not shared)

Best Answer

Answers

  • RaylightRaylight Member ✭✭
    edited September 2018

    Update : found some answer (i hope cause still have error and can't test the code) var webClient = new WebClient(); webClient.DownloadDataCompleted += (s, e) => { var bytes = e.Result; string documentsPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal); string localFilename = "checklist.zip"; string localPath = Path.Combine(documentsPath, localFilename); File.WriteAllBytes(documentsPath, bytes); }; webClient.DownloadDataAsync(new Uri(url));

    Now i got this error : System.UnauthorizedAccessException: 'Access to the path "any path it tried' is denied.
    Have seen a lot of people with the same troubles (already tried git read/write access to the app in android.manifest).
    If you think i'm on the right way to resolve my first question please tell me and if you have some clues every help is welcome !

  • RaylightRaylight Member ✭✭

    Update : i'm so desesparate, don't manage to made the last sample wrking.
    I'm now reduce to use Device.OpenUri to download my file.
    Anyone can help ?

  • JoeMankeJoeManke USMember ✭✭✭✭✭

    Environment.SpecialFolder.MyDocuments or Environment.SpecialFolder.LocalApplicationData should get your app's local storage directory which does not require any permissions to write to.

  • RaylightRaylight Member ✭✭

    First of all thanks for the answer.
    I manage to get trought the permissions but my main problem is still here : i can't find a sample to hit an URL who's gonna start my download, i got an '****.php' file when i use the downloadManager plugin and the sample with webclient just don't do anything.

  • JoeMankeJoeManke USMember ✭✭✭✭✭

    So you're looking for a URL to test against?

  • RaylightRaylight Member ✭✭
    edited September 2018
    No, i got a URL and i try to hit it so my download start (i mean, if i paste the URL on my browser the download start bye himself that's why i use Device.OpenUri(New Uri(myurl)) ; to do the job but i'm searching for a proper way to do that within my app)
    Sorry for my english ..
  • RaylightRaylight Member ✭✭
    Thanks for the answer, i will try !
  • Anderson_VieiraAnderson_Vieira Member ✭✭
    edited September 2018

    @Raylight Do you still need help? I have some applications that do exactly what you want to do, downloading files, If I need to put it here for you.

  • RaylightRaylight Member ✭✭

    @Daxton47 in my case the URL made me download a .zip automatically when open(the url is a download link), i have tried you'r sample and when i hit the button in the app (wich trigger you'r sample with a given Url) nothing happen except a short wifi activity, but nothing is download (have tried with several URL bye the way)

    @Anderson_Vieira yup still need help please

  • Daxton47Daxton47 Member ✭✭

    @Raylight
    Interesting! I'm testing it with .zip files now and it seems to be working... What is that method returning in the byte array? Is it empty or is it populated?

  • Anderson_VieiraAnderson_Vieira Member ✭✭
    edited September 2018

    @Raylight

    In android:

              public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
                {
     protected override void OnCreate(Bundle bundle)
            {
    
            ................................................... 
              base.OnCreate(bundle);
    
    
            Downloaded();
    
             Forms.Init(this, bundle);
    
    
               }
    }
     public void Downloaded()
            {
                CrossDownloadManager.Current.PathNameForDownloadedFile =
                    new Func<IDownloadFile, string>(file =>
                    {
                        string fileName = Android.Net.Uri.Parse(file.Url).Path.Split('/').Last();
                        return System.IO.Path.Combine(ApplicationContext.GetExternalFilesDir(
                            Android.OS.Environment.DirectoryDownloads).AbsolutePath, fileName);
                    });
            }
    

    PCL MVVM:

                     public class Product : INotifyPropertyChanged
                        {
    
                    public Product(){
                     CrossDownloadManager.Current.CollectionChanged += (sender, e) =>
                                   System.Diagnostics.Debug.WriteLine(
                                       "[DownloadManager] " + e.Action +
                                       " -> New items: " + (e.NewItems?.Count ?? 0) +
                                       " at " + e.NewStartingIndex +
                                       " || Old items: " + (e.OldItems?.Count ?? 0) +
                                       " at " + e.OldStartingIndex
                                   );
                    }
    
                    public ICommand DownCommand {
                                get {
                                    return new RelayCommand(Save);
                                }
                            }
                             void Save()
                            {
    
                                  DownloadFile(VideoLink);
                                 // DownloadFile(https://www.sample-videos.com/video/mp4/240/big_buck_bunny_240p_50mb.mp4); 
                              //    DependencyService.Get<IMessage>().LongAlert("Seu vídeo está sendo baixado!");
    
    
                            }
                            public async void DownloadFile(String FileName)
                            {
                                await Task.Yield();
                                //  await Navigation.PushPopupAsync(new DownloadingPage());
                                await Task.Run(() =>
                                {
                                    var downloadManager = CrossDownloadManager.Current;
                                    var file = downloadManager.CreateDownloadFile(FileName);
                                    downloadManager.Start(file, true);
                                    while (isDownloading)
                                    {
                                        isDownloading = IsDownloading(file);
                                    }
                                });
                                if (isDownloading)
                                {
    
                                   // await DisplayAlert("Status", "Arquivo baixado", "OK");
                                    // DependencyService.Get<IToast>().ShowToast("");
                                }
                            }
                            public void StartDownloading(bool mobileNetworkAllowed)
                            {
                                CrossDownloadManager.Current.Start(File, mobileNetworkAllowed);
                            }
    
                            public void AbortDownloading()
                            {
                                CrossDownloadManager.Current.Abort(File);
                            }
                            public bool IsDownloading(IDownloadFile File)
                            {
                                if (File == null) {
                                    return false;
                                }
    
                                switch (File.Status)
                                {
                                    case DownloadFileStatus.INITIALIZED:
                                    case DownloadFileStatus.PAUSED:
                                    case DownloadFileStatus.PENDING:
                                    case DownloadFileStatus.RUNNING:
                                        return true;
    
                                    case DownloadFileStatus.COMPLETED:
                                    case DownloadFileStatus.CANCELED:
                                    case DownloadFileStatus.FAILED:
                                        return false;
                                    default:
                                        throw new ArgumentOutOfRangeException();
                                }
                            }
    
                    }
    

    Permissions:
    uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"

    With the help of some references, I put in the MVVM format to make the code more organized, if you do not care for it, you can put in the codebehind that will give it.

    https://github.com/nekszer/Download-Forms
    https://www.nuget.org/packages/Xam.Plugins.DownloadManager/
    https://github.com/SimonSimCity/Xamarin-CrossDownloadManager

  • RaylightRaylight Member ✭✭

    @Daxton47 Hi, i've tried to print the byte array but i got a 'System.ArgumentNullException: Array cannot be null.', in my case this null value come from the 'catch (exception)', not sure why but i will try to figure it out.

    @Anderson_Vieira I already tried DownloadManager and i'm searching for a xamarin.forms cross platform solution, i'm not even sure that i can still create PCL project with latest update of vs 2017, but thanks for your help !

  • @Raylight You can, if your project is public, send the link that I add there to you if you want. is something simple, so I opted for it, you can download all types of files and still do customizations per platform.

  • RaylightRaylight Member ✭✭

    @Anderson_Vieira Ok, will try DownloadManager again with your sample !

  • @Raylight Yes, I told you in the beginning that I put it in mvvm, I copied this code from my own project, I mentioned the sources in case you wanted to do some customization, it works perfectly with visual studio 2017, it does not interfere with anything.

Sign In or Register to comment.