Android实现上传文件功能的方法主要有两种:使用HttpURLConnection或使用OkHttp库。
Android实现上传文件功能的方法主要有两种:使用HttpURLConnection或使用OkHttp库。
使用HttpURLConnection上传文件
步骤一:添加网络权限
在AndroidManifest.xml文件中添加以下权限:
<uses-permission android:name="android.permission.INTERNET" />
步骤二:创建一个上传文件的方法
private void uploadFile(String filePath, String serverUrl) {
try {
URL url = new URL(serverUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=****");
OutputStream outputStream = new DataOutputStream(conn.getOutputStream());
String boundary = "****";
StringBuilder builder = new StringBuilder();
builder.append("--").append(boundary).append("\r\n");
builder.append("Content-Disposition: form-data; name=\"file\"; filename=\"").append(filePath).append("\"\r\n");
builder.append("Content-Type: application/octet-stream; charset=UTF-8\r\n\r\n");
outputStream.write(builder.toString().getBytes());
FileInputStream fileInputStream = new FileInputStream(filePath);
byte[] buffer = new byte[1024 * 1024];
int length;
while ((length = fileInputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, length);
}
outputStream.write("\r\n--".getBytes());
outputStream.write(boundary.getBytes());
outputStream.write("--\r\n");
outputStream.flush();
fileInputStream.close();
outputStream.close();
int code = conn.getResponseCode();
InputStream inputStream = conn.getInputStream();
StringBuilder stringBuilder = new StringBuilder();
byte[] codeBuffer = new byte[1024];
while (inputStream.read(codeBuffer) != -1) {
stringBuilder.append(new String(codeBuffer));
}
inputStream.close();
if (code == HttpURLConnection.HTTP_OK) {
Log.i("TAG", "上传成功:" + stringBuilder.toString());
} else {
Log.i("TAG", "上传失败:" + stringBuilder.toString());
}
} catch (Exception e) {
e.printStackTrace();
}
}
其中,filePath参数是文件的路径,serverUrl参数是要上传的服务器地址。使用HttpURLConnection上传文件需要注意:
- 请求方式必须是POST;
- 请求头必须设置Content-Type为multipart/form-data;
- 请求体中要包含文件部分的内容。
步骤三:调用上传文件方法
uploadFile("/sdcard/test.txt", "http://www.example.com/upload");
使用OkHttp上传文件
步骤一:添加OkHttp依赖
在app/build.gradle文件中添加OkHttp依赖:
dependencies {
implementation 'com.squareup.okhttp3:okhttp:4.8.1'
}
步骤二:创建一个上传文件的方法
private void uploadFile(String filePath, String serverUrl) {
try {
OkHttpClient okHttpClient = new OkHttpClient();
File file = new File(filePath);
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("file", file.getName(), RequestBody.create(MediaType.parse("multipart/form-data"), file))
.build();
Request request = new Request.Builder()
.url(serverUrl)
.post(requestBody)
.build();
Response response = okHttpClient.newCall(request).execute();
if (response.isSuccessful()) {
String result = response.body().string();
Log.i("TAG", "上传成功:" + result);
} else {
String result = response.body().string();
Log.i("TAG", "上传失败:" + result);
}
} catch (Exception e) {
e.printStackTrace();
}
}
其中,filePath参数是文件的路径,serverUrl参数是要上传的服务器地址。使用OkHttp上传文件可以直接创建RequestBody,然后使用MultipartBody来添加文件的内容。注意要将Content-Type设置为multipart/form-data。
步骤三:调用上传文件方法
uploadFile("/sdcard/test.txt", "http://www.example.com/upload");
以上是两种实现Android文件上传功能的方法,可以根据自己的需求选择其中一种。
沃梦达教程
本文标题为:Android实现上传文件功能的方法
猜你喜欢
- java 解决Eclipse挂掉问题的方法 2023-12-27
- MyBatis-Plus详解(环境搭建、关联操作) 2023-05-14
- springBoot详解集成Swagger流程 2023-02-05
- java实现单链表中的增删改 2022-11-12
- SpringBoot-application.yml多环境配置详解 2023-03-16
- SpringCloud服务网关Gateway的使用教程详解 2023-05-18
- Java easyexcel使用教程之导出篇 2022-12-07
- Java+JFrame实现贪吃蛇小游戏 2022-12-07
- java词法分析器DDL递归应用详解 2023-03-06
- ClassLoader双亲委派模式作用详解 2023-06-30