簡體   English   中英

Android將任何文件上傳到服務器

[英]Android uploading ANY file to Server

我正在開發一個應用程序,用戶可以從SD卡中選擇任何文件並將其上傳到服務器。 用戶還可以單擊相機中的圖像並上傳圖像。 這可以正常工作,但是當我嘗試從文件資源管理器中選擇任何其他文件時,它根本不起作用。

讓用戶選擇任何文件的代碼:

Intent intent = new Intent(Intent.ACTION_GET_CONTENT); 
    intent.setType("file/*"); 
    intent.addCategory(Intent.CATEGORY_OPENABLE);

    try {
        startActivityForResult(Intent.createChooser(intent, "Complete action using"), GET_FILE_REQUEST_CODE);
    }
    catch (Exception ex) {
        Toast.makeText(getActivity(), "Please install any File Manager to complete the task.", Toast.LENGTH_SHORT).show();
    }

從活動獲取結果的代碼:

if (resultCode == getActivity().RESULT_OK) {
            Uri uri = Uri.parse(data.getData().toString());
            File myfile=new File(uri.getPath());
            sendSelectedFileURI(myfile.getAbsolutePath());
            Log.d("patho",uri.getPath());
            Log.d("path",myfile.getAbsolutePath());
        } else if (resultCode == getActivity().RESULT_CANCELED) {


        } else {
            Toast.makeText(getActivity(),
                    "Error", Toast.LENGTH_SHORT)
                    .show();
        }

然后,我只是創建文件,並將其作為FileBody添加到HttpEntity,如下所示:

File sourceFile=new File(filepath);
entity.addPart("image", new FileBody(sourceFile));

在某些設備中,我得到了正確的路徑,並且文件被上傳到服務器,在某些設備中,它引發了File not found異常。 它在我創建FileBody的那一行上引發錯誤。

因此,我想要的是用戶可以從SD卡中選擇任何類型的文件,然后選擇要上傳到服務器上的文件。

參考以下鏈接后,我解決了該問題。

從Android Kitkat中的Uri獲取路徑會引發非法參數異常

基本上,我們需要在KitKat及更高版本上檢查DocumentURI。

暫無
暫無

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

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