Android上傳文件的全面解析

一、從Android上傳文件到SpringBoot

在開發過程中,經常需要上傳文件到後端服務器。這裡介紹一種將Android文件上傳到SpringBoot服務器的方法。主要過程如下:

1、在Android中選擇文件

    private static final int FILE_SELECT_CODE = 1;

    private void showFileChooser() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("*/*");
        intent.addCategory(Intent.CATEGORY_OPENABLE);

        try {
            startActivityForResult(Intent.createChooser(intent, "請選擇一個文件"), FILE_SELECT_CODE);
        } catch (android.content.ActivityNotFoundException ex) {
            // no file manager installed
        }
    }

2、在Android中上傳文件

    if (resultCode == RESULT_OK) {
        if (requestCode == FILE_SELECT_CODE) {
            // Get the Uri of the selected file
            Uri uri = data.getData();
            String filePath = FileUtils.getPath(this, uri);
            Log.d(TAG, "file path:" + filePath);
            uploadFile(filePath);
        }
    }

    private void uploadFile(String filePath) {
        if (filePath == null) {
            Toast.makeText(this, "請選擇文件", Toast.LENGTH_SHORT).show();
            return;
        }
        File file = new File(filePath);
        RequestBody fileBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
        MultipartBody.Part body = MultipartBody.Part.createFormData("file", file.getName(), fileBody);

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://localhost:8080/")//後端地址
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        UploadService uploadService = retrofit.create(UploadService.class);
        Call<Result> resultCall = uploadService.uploadFile(body);
        resultCall.enqueue(new Callback<Result>() {
            @Override
            public void onResponse(Call<Result> call, Response<Result> response) {
                Result result = response.body();
                if (result.isSuccess()) {
                    Toast.makeText(MainActivity.this, "上傳成功", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(MainActivity.this, result.getMessage(), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<Result> call, Throwable t) {
                Toast.makeText(MainActivity.this, "上傳失敗", Toast.LENGTH_SHORT).show();
            }
        });
    }

3、後端使用SpringBoot接收文件

    @PostMapping("/uploadFile")
    public Result uploadFile(@RequestParam("file") MultipartFile file) {
        if (!file.isEmpty()) {
            String fileName = file.getOriginalFilename();
            String filePath = "d:/upload/";
            File dest = new File(filePath + fileName);
            try {
                file.transferTo(dest);
                return Result.success("上傳成功");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return Result.fail("沒有選擇文件");
    }

二、Android上傳文件控件

除了手動選擇文件上傳外,還可以使用第三方上傳文件控件,例如百度雲提供的開源控件BOSUploadFileSDK。

    compile 'com.baidu:bos-upload-sdk:1.0.3'
    //...

    BosUploadFileSDK.getInstance(this, AK, SK, endpoint, bucketName)
            .selectFileAndUpload(new OnUploadListener() {...});

三、Android文件選擇和上傳

一個通用的Android文件選擇和上傳示例:

    EditText filePathET;//顯示文件路徑的文本框
    Button chooseFileBT;//點擊選擇文件的按鈕
    Button uploadBT;//點擊上傳按鈕
    ProgressBar uploadPB;//顯示上傳進度

    String filePath;//上傳文件的路徑

    private void chooseFile() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("*/*");
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        try {
            startActivityForResult(Intent.createChooser(intent, "請選擇要上傳的文件"), 1);
        } catch (ActivityNotFoundException ex) {
            showToast("請先安裝一個文件管理程序");
        }
    }

    private void uploadFile() {
        if (filePath == null) {
            showToast("請選擇要上傳的文件");
            return;
        }
        File file = new File(filePath);
        RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);
        MultipartBody.Part body = MultipartBody.Part.createFormData("file", file.getName(), requestFile);

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        UploadService uploadService = retrofit.create(UploadService.class);
        Call<Result> call = uploadService.uploadFile(body);
        call.enqueue(new Callback<Result>() {
            @Override
            public void onResponse(Call<Result> call, Response<Result> response) {
                Result result = response.body();
                if (result != null && result.isSuccess()) {
                    showToast("上傳成功");
                } else {
                    showToast("上傳失敗");
                }
            }

            @Override
            public void onFailure(Call<Result> call, Throwable t) {
                showToast("上傳失敗");
            }
        });
    }

四、Android上傳文件源碼和PHP源碼

Android上傳文件源碼和後端PHP源碼:

Android源碼:

    private void uploadFile() {
        if (filePath == null) {
            showToast("請選擇要上傳的文件");
            return;
        }
        File file = new File(filePath);
        RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);
        MultipartBody.Part body = MultipartBody.Part.createFormData("file", file.getName(), requestFile);

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        UploadService uploadService = retrofit.create(UploadService.class);
        Call<Result> call = uploadService.uploadFile(body);
        call.enqueue(new Callback<Result>() {
            @Override
            public void onResponse(Call<Result> call, Response<Result> response) {
                Result result = response.body();
                if (result != null && result.isSuccess()) {
                    showToast("上傳成功");
                } else {
                    showToast("上傳失敗");
                }
            }

            @Override
            public void onFailure(Call<Result> call, Throwable t) {
                showToast("上傳失敗");
            }
        });
    }

PHP源碼:

    <?php
    $file=$_FILES['file'];
    $info=pathinfo($file['name']);
    $ext=$info['extension'];
    $types=array("jpg","png","gif","bmp");
    if(!in_array($ext,$types)){
        exit("格式錯誤,只支持後綴為jpg、png、gif、bmp的文件!");
    }
    $path="./uploads/".$file['name'];
    $tmp=$file['tmp_name'];
    move_uploaded_file($tmp,$path);//移動上傳文件
    echo "上傳成功!";
    ?>

五、Android和iOS傳文件

Android和iOS傳文件使用的是相同的協議,可以使用同一套代碼來實現文件的上傳和下載。

六、Android上傳文件到服務器

上傳文件到服務器需要先在Android客戶端進行文件的選擇和上傳,並將文件流通過HTTP請求發送到服務器。服務器端則需要解析HTTP請求,及時接收並處理上傳的文件。Android客戶端使用Apache HttpClient發起請求,服務器端使用SpringBoot來接收請求並處理文件。

七、Android上傳文件到雲端

Android上傳文件到雲端,可以使用雲存儲服務,例如阿里雲OSS、騰訊雲COS等。

    // AliOSS示例代碼
    private OSS oss;

    private void initOss(String endpoint, String accessKeyId, String accessKeySecret, String bucketName) {
        OSSCredentialProvider credentialProvider = new OSSPlainTextAKSKCredentialProvider(accessKeyId, accessKeySecret);
        ClientConfiguration configuration = new ClientConfiguration();
        configuration.setConnectionTimeout(15 * 1000);
        configuration.setSocketTimeout(15 * 1000);

        oss = new OSSClient(getApplicationContext(), endpoint, credentialProvider, configuration);
    }

    private void uploadToAliOSS(String objectKey, String filePath) {
        PutObjectRequest put = new PutObjectRequest(bucketName, objectKey, filePath);
        oss.asyncPutObject(put, new OSSCompletedCallback() {
            @Override
            public void onSuccess(PutObjectRequest request, PutObjectResult result) {
                showToast("上傳成功");
            }

            @Override
            public void onFailure(PutObjectRequest request, ClientException clientException, ServiceException serviceException) {
                showToast("上傳失敗");
            }
        });
    }

八、Android上傳文件到倉庫

Android上傳文件到倉庫,可以使用第三方倉庫服務,例如MavenCentral倉庫中的nexus-staging-maven-plugin插件。

    // Gradle示例代碼
    apply plugin: 'maven-publish'

    publishing {
        publications {
            maven(MavenPublication) {
                groupId "com.example"
                artifactId "library"
                version "1.0.0"
                artifact("$buildDir/outputs/aar/library-release.aar")
            }
        }
        repositories {
            maven {
                url 'http://localhost:8081/repository/maven-releases/'
                credentials {
                    username 'admin'
                    password 'admin'
                }
            }
        }
    }

九、Android上傳文件到OSS

Android上傳文件到OSS,可以使用阿里雲OSS提供的Java SDK。

    // Gradle示例代碼
    implementation 'com.aliyun.oss:aliyun-sdk-oss:2.9.2'

    // Java示例代碼
    OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
    InputStream inputStream = new FileInputStream("local_file_path");
    PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, inputStream);
    PutObjectResult putObjectResult = ossClient.putObject(putObjectRequest);
    ossClient.shutdown();

十、亞馬遜S3 Android上傳文件

亞馬遜S3 Android上傳文件需要在Android客戶端集成亞馬遜提供的AWSService SDK。

    // Gradle示例代碼
    implementation 'com.amazonaws:aws-android-sdk-s3:2.5.6'

    // Java示例代碼
    AmazonS3 s3Client = new AmazonS3Client(new BasicAWSCredentials(accessKeyId, secretKey));
    s3Client.setRegion(Region.getRegion(Regions.fromName(region)));

    PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, file);
    s3Client.putObject(putObjectRequest);

原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/151247.html

(0)
打賞 微信掃一掃 微信掃一掃 支付寶掃一掃 支付寶掃一掃
小藍的頭像小藍
上一篇 2024-11-11 13:40
下一篇 2024-11-11 13:40

相關推薦

  • Python應用程序的全面指南

    Python是一種功能強大而簡單易學的編程語言,適用於多種應用場景。本篇文章將從多個方面介紹Python如何應用於開發應用程序。 一、Web應用程序 目前,基於Python的Web…

    編程 2025-04-29
  • Python zscore函數全面解析

    本文將介紹什麼是zscore函數,它在數據分析中的作用以及如何使用Python實現zscore函數,為讀者提供全面的指導。 一、zscore函數的概念 zscore函數是一種用於標…

    編程 2025-04-29
  • 全面解讀數據屬性r/w

    數據屬性r/w是指數據屬性的可讀/可寫性,它在程序設計中扮演着非常重要的角色。下面我們從多個方面對數據屬性r/w進行詳細的闡述。 一、r/w的概念 數據屬性r/w即指數據屬性的可讀…

    編程 2025-04-29
  • Python計算機程序代碼全面介紹

    本文將從多個方面對Python計算機程序代碼進行詳細介紹,包括基礎語法、數據類型、控制語句、函數、模塊及面向對象編程等。 一、基礎語法 Python是一種解釋型、面向對象、動態數據…

    編程 2025-04-29
  • Matlab二值圖像全面解析

    本文將全面介紹Matlab二值圖像的相關知識,包括二值圖像的基本原理、如何對二值圖像進行處理、如何從二值圖像中提取信息等等。通過本文的學習,你將能夠掌握Matlab二值圖像的基本操…

    編程 2025-04-28
  • 瘋狂Python講義的全面掌握與實踐

    本文將從多個方面對瘋狂Python講義進行詳細的闡述,幫助讀者全面了解Python編程,掌握瘋狂Python講義的實現方法。 一、Python基礎語法 Python基礎語法是學習P…

    編程 2025-04-28
  • 全面解析Python中的Variable

    Variable是Python中常見的一個概念,是我們在編程中經常用到的一個變量類型。Python是一門強類型語言,即每個變量都有一個對應的類型,不能無限制地進行類型間轉換。在本篇…

    編程 2025-04-28
  • Zookeeper ACL 用戶 anyone 全面解析

    本文將從以下幾個方面對Zookeeper ACL中的用戶anyone進行全面的解析,並為讀者提供相關的示例代碼。 一、anyone 的作用是什麼? 在Zookeeper中,anyo…

    編程 2025-04-28
  • Python合集符號全面解析

    Python是一門非常流行的編程語言,在其語法中有一些特殊的符號被稱作合集符號,這些符號在Python中起到非常重要的作用。本文將從多個方面對Python合集符號進行詳細闡述,幫助…

    編程 2025-04-28
  • Switchlight的全面解析

    Switchlight是一個高效的輕量級Web框架,為開發者提供了簡單易用的API和豐富的工具,可以快速構建Web應用程序。在本文中,我們將從多個方面闡述Switchlight的特…

    編程 2025-04-28

發表回復

登錄後才能評論