Android上傳給服務(wù)器
在Android應(yīng)用開發(fā)中,與服務(wù)器進行數(shù)據(jù)交互是常見的需求,本文將詳細介紹如何在Android應(yīng)用中實現(xiàn)文件上傳功能,包括選擇文件、壓縮文件(可選)、上傳文件到服務(wù)器以及處理服務(wù)器響應(yīng),以下是詳細的步驟和代碼示例:
準備工作
1.1 添加依賴
在項目的build.gradle
文件中添加必要的依賴,例如用于網(wǎng)絡(luò)請求的OkHttp庫和用于JSON解析的Gson庫。
dependencies { implementation 'com.squareup.okhttp3:okhttp:4.9.0' implementation 'com.google.code.gson:gson:2.8.6' }
1.2 權(quán)限聲明
在AndroidManifest.xml
中聲明必要的權(quán)限,例如互聯(lián)網(wǎng)訪問權(quán)限和讀寫存儲權(quán)限。
<uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
選擇文件
使用Intent
讓用戶從設(shè)備中選擇一個文件。
private void chooseFile() { Intent intent = new Intent(Intent.ACTION_GET_CONTENT); intent.setType("*/*"); intent.addCategory(Intent.CATEGORY_OPENABLE); try { startActivityForResult(Intent.createChooser(intent, "Select a File to Upload"), FILE_SELECT_CODE); } catch (android.content.ActivityNotFoundException ex) { // Potentially handle the error here } }
壓縮文件(可選)
如果需要對文件進行壓縮,可以使用ZipOutputStream類。
private File compressFile(File file) throws IOException { File zipFile = new File(file.getParent(), file.getName() + ".zip"); try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFile))) { zos.putNextEntry(new ZipEntry(file.getName())); byte[] bytes = new byte[1024]; int length; try (FileInputStream fis = new FileInputStream(file)) { while ((length = fis.read(bytes)) >= 0) { zos.write(bytes, 0, length); } } zos.closeEntry(); } return zipFile; }
上傳文件到服務(wù)器
使用OkHttp庫上傳文件到服務(wù)器。
private void uploadFile(File file) { // Create a multipart request body RequestBody filePart = RequestBody.create(MediaType.parse("application/octet-stream"), file); MultipartBody requestBody = new MultipartBody.Builder() .setType(MultipartBody.FORM) .addFormDataPart("file", file.getName(), filePart) .build(); // Create the request Request request = new Request.Builder() .url("https://yourserver.com/upload") .post(requestBody) .build(); // Add the request to the client and execute it OkHttpClient client = new OkHttpClient(); client.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, Response response) { // Handle the failure } @Override public void onResponse(Call call, Response response) throws IOException { if (!response.isSuccessful()) throw new IOException("Unexpected code " + response); // Handle the response } }); }
處理服務(wù)器響應(yīng)
根據(jù)服務(wù)器返回的數(shù)據(jù)格式,解析響應(yīng)并更新UI。
client.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, Response response) { // Handle the failure } @Override public void onResponse(Call call, Response response) throws IOException { if (!response.isSuccessful()) throw new IOException("Unexpected code " + response); // Assuming the server returns a JSON response String jsonData = response.body().string(); // Parse the JSON data using Gson or any other library } });
完整示例代碼
以下是一個完整的示例代碼,展示了如何實現(xiàn)上述功能。
public class MainActivity extends AppCompatActivity { private static final int FILE_SELECT_CODE = 1; private OkHttpClient client = new OkHttpClient(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); findViewById(R.id.btnChooseFile).setOnClickListener(v -> chooseFile()); } private void chooseFile() { Intent intent = new Intent(Intent.ACTION_GET_CONTENT); intent.setType("*/*"); intent.addCategory(Intent.CATEGORY_OPENABLE); try { startActivityForResult(Intent.createChooser(intent, "Select a File to Upload"), FILE_SELECT_CODE); } catch (android.content.ActivityNotFoundException ex) { // Potentially handle the error here } } @Override protected void onActivityResult(int requestCode, int resultCode, int data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == FILE_SELECT_CODE && resultCode == RESULT_OK && data != null) { Uri fileUri = data.getData(); try { File file = new File(requireNotNull(fileUri).getPath()); File compressedFile = compressFile(file); // Compress if needed uploadFile(compressedFile); } catch (IOException e) { e.printStackTrace(); } } } private File compressFile(File file) throws IOException { File zipFile = new File(file.getParent(), file.getName() + ".zip"); try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFile))) { zos.putNextEntry(new ZipEntry(file.getName())); byte[] bytes = new byte[1024]; int length; try (FileInputStream fis = new FileInputStream(file)) { while ((length = fis.read(bytes)) >= 0) { zos.write(bytes, 0, length); } } zos.closeEntry(); } return zipFile; } private void uploadFile(File file) { RequestBody filePart = RequestBody.create(MediaType.parse("application/octet-stream"), file); MultipartBody requestBody = new MultipartBody.Builder() .setType(MultipartBody.FORM) .addFormDataPart("file", file.getName(), filePart) .build(); Request request = new Request.Builder() .url("https://yourserver.com/upload") .post(requestBody) .build(); client.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, Response response) { // Handle the failure } @Override public void onResponse(Call call, Response response) throws IOException { if (!response.isSuccessful()) throw new IOException("Unexpected code " + response); String jsonData = response.body().string(); // Parse the JSON data using Gson or any other library } }); } }