Android上传给服务器
在Android应用开发中,与服务器进行数据交互是常见的需求,本文将详细介绍如何在Android应用中实现文件上传功能,包括选择文件、压缩文件(可选)、上传文件到服务器以及处理服务器响应,以下是详细的步骤和代码示例:
准备工作
1.1 添加依赖
在项目的build.gradle
文件中添加必要的依赖,例如用于网络请求的OkHttp库和用于JSON解析的Gson库。
dependencies { implementation 'com.squareup.okhttp3:okhttp:4.9.0' implementation 'com.google.code.gson:gson:2.8.6' }
1.2 权限声明
在AndroidManifest.xml
中声明必要的权限,例如互联网访问权限和读写存储权限。
<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
让用户从设备中选择一个文件。
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; }
上传文件到服务器
使用OkHttp库上传文件到服务器。
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 } }); }
处理服务器响应
根据服务器返回的数据格式,解析响应并更新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 } });
完整示例代码
以下是一个完整的示例代码,展示了如何实现上述功能。
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 } }); } }
原创文章,作者:未希,如若转载,请注明出处:https://www.kdun.com/ask/1257296.html
本网站发布或转载的文章及图片均来自网络,其原创性以及文中表达的观点和判断不代表本网站。如有问题,请联系客服处理。
发表回复