一、從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