您的位置:

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
   > resultCall = uploadService.uploadFile(body);
        resultCall.enqueue(new Callback
    
     >() {
            @Override
            public void onResponse(Call
      
       
        > call, Response
        
         
          > 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
           
            
             > 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
   > call = uploadService.uploadFile(body);
        call.enqueue(new Callback
    
     >() {
            @Override
            public void onResponse(Call
      
       
        > call, Response
        
         
          > response) { Result
          
           result = response.body(); if (result != null && result.isSuccess()) { showToast("上传成功"); } else { showToast("上传失败"); } } @Override public void onFailure(Call
           
            
             > 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
   > call = uploadService.uploadFile(body);
        call.enqueue(new Callback
    
     >() {
            @Override
            public void onResponse(Call
      
       
        > call, Response
        
         
          > response) { Result
          
           result = response.body(); if (result != null && result.isSuccess()) { showToast("上传成功"); } else { showToast("上传失败"); } } @Override public void onFailure(Call
           
            
             > 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);