簡體   English   中英

如何從Xamarin的內部或外部存儲上傳任何文件?

[英]How to Upload Any file from internal or External Storage in Xamarin?

我已經編寫了用於選擇圖像並上傳圖像並在模擬器中獲取特定圖像的代碼,但是如何使用Xamarin從Android文件系統訪問任何文件,那么我應該怎么做呢?

namespace XAFileUpload_2._0
{
    [Activity(Label = "XAFileUpload 2.0", MainLauncher = true, Icon = "@drawable/icon")]
    public class MainActivity : Activity
    {

        //Pick Id to know the pick item no.
        public static readonly int PickImageId = 1000;

        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

            // Set our view from the "main" layout resource
            SetContentView (Resource.Layout.Main);

            Button button = FindViewById<Button>(Resource.Id.Browse);
            button.Click += BrowseButtonOnClick;

        }

        void BrowseButtonOnClick(object sender, EventArgs eventArs)
        {
            Intent = new Intent();
            Intent.SetType("image/*");
            Intent data = Intent.SetAction(Intent.ActionGetContent);

            try
            {
                StartActivityForResult(Intent.CreateChooser(Intent, "Select Picture"), PickImageId);
            }
            catch (ActivityNotFoundException ex)
            {
                Toast.MakeText(this, "Please install a File Manager.", ToastLength.Long).Show();
            }
            catch (Exception ex)
            {
                Toast.MakeText(this, "Error occured ", ToastLength.Long).Show();
            }
        }

        protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
        {
            if ((requestCode == PickImageId) && (resultCode == Result.Ok) && (data != null))
            {
                UploadFile(data);

            }
        }

        void UploadFile(Intent data)
        {
            ICursor cursor = null;

            try
            {
                Button upButton = FindViewById<Button>(Resource.Id.Upload);

                // assuming image
                var docID = DocumentsContract.GetDocumentId(data.Data);
                var id = docID.Split(':')[1];
                var whereSelect = MediaStore.Images.ImageColumns.Id + "=?";
                var projections = new string[] { MediaStore.Images.ImageColumns.Data };
                // Try internal storage first
                cursor = ContentResolver.Query(MediaStore.Images.Media.InternalContentUri, projections, whereSelect, new string[] { id }, null);
                if (cursor.Count == 0)
                {
                    // not found on internal storage, try external storage
                    cursor = ContentResolver.Query(MediaStore.Images.Media.ExternalContentUri, projections, whereSelect, new string[] { id }, null);
                }
                var colData = cursor.GetColumnIndexOrThrow(MediaStore.Images.ImageColumns.Data);
                cursor.MoveToFirst();
                var fullPathToImage = cursor.GetString(colData);
                string fpti = cursor.GetString(colData);

                string address = "http://192.168.3.157:82/Values/DownFile";


                upButton.Click += (sender, args) =>
                {
                    try
                    {
                        ProgressDialog progressDialog = new ProgressDialog(this);
                        progressDialog.SetTitle("Please wait...");
                        progressDialog.SetCancelable(false);

                        Task.Run(() =>
                        {

                            RunOnUiThread(() =>
                            {
                                progressDialog.Show();
                            });

                            using (WebClient client = new WebClient())
                            {
                                client.UploadFile(address, fullPathToImage);

                            }

                            RunOnUiThread(() =>
                            {

                                progressDialog.Dismiss();

                                string msg = "Upload Completed";
                                Toast.MakeText(this, msg, ToastLength.Long).Show();

                            });
                        });
                    }
                    catch (Exception ex)
                    {
                        Log.Error("MediaPath", ex.Message);
                    }
                };
            }
            catch (Exception ex)
            {
                Log.Error("MediaPath", ex.Message);
            }
            finally
            {

                cursor?.Close();
                cursor?.Dispose();
            }
        }
    }
}

看看以下內容

string path = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
string filename = Path.Combine(path, "myfile.txt");

using (var streamWriter = new StreamWriter(filename, true))
{
    streamWriter.WriteLine(DateTime.UtcNow);
}

using (var streamReader = new StreamReader(filename))
{
    string content = streamReader.ReadToEnd();
    System.Diagnostics.Debug.WriteLine(content);
}
Intent = new Intent();
            Intent.SetType("image/*");
            Intent.SetAction(Intent.ActionGetContent);
            StartActivityForResult(Intent.CreateChooser(Intent, "Select Picture"), PickImageId);

打開圖像拾取對話框,選擇圖像后自動調用OnActivityResult方法

protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
    {
        if ((requestCode == PickImageId) && (resultCode == Result.Ok) && (data != null))
        {
        //Your code to upload image. 
        //image uri is in data object.
        }
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM