用Java来写APP上传头像代码实现流程
1. 确定需求和基本步骤
在实现用Java来写APP上传头像代码之前,我们先来确定一下整个流程。下面是实现该功能的基本步骤:
步骤 | 描述 |
---|---|
1 | 获取用户选择的图片 |
2 | 压缩图片 |
3 | 上传图片到服务器 |
4 | 返回图片的URL |
2. 详细步骤及代码实现
步骤1:获取用户选择的图片
在这一步中,我们需要让用户选择一张图片作为头像。可以通过使用Android提供的Intent
来打开系统相册,让用户选择需要上传的图片。
代码实现如下:
Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, PICK_IMAGE_REQUEST);
步骤2:压缩图片
为了减小图片的文件大小,我们需要对选择的图片进行压缩。可以使用Android提供的BitmapFactory
类来实现图片的压缩。
代码实现如下:
public Bitmap compressImage(Bitmap image) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.JPEG, 100, baos);
int options = 90;
while (baos.toByteArray().length / 1024 > 100 && options > 10) {
baos.reset();
image.compress(Bitmap.CompressFormat.JPEG, options, baos);
options -= 10;
}
ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());
Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);
return bitmap;
}
步骤3:上传图片到服务器
在这一步中,我们需要将压缩后的图片上传到服务器。可以使用HTTP请求来实现图片的上传,这里我们使用HttpURLConnection
来发送POST请求。
代码实现如下:
public String uploadImage(Bitmap image) {
String boundary = "*****";
String lineEnd = "\r\n";
String twoHyphens = "--";
try {
URL url = new URL(SERVER_URL);
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=" + boundary);
DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"image\";filename=\"" + fileName + "\"" + lineEnd);
dos.writeBytes(lineEnd);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageData = baos.toByteArray();
dos.write(imageData);
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
dos.flush();
dos.close();
// 获取服务器的响应
InputStream is = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String line;
StringBuilder response = new StringBuilder();
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();
is.close();
return response.toString();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
步骤4:返回图片的URL
服务器返回的响应中包含了上传后图片的URL。在这一步中,我们需要解析服务器返回的JSON数据,获取到图片的URL。
代码实现如下:
public String getImageUrlFromResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
String imageUrl = jsonObject.getString("url");
return imageUrl;
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
3. 状态图
下面是整个上传头像的流程的状态图:
stateDiagram
[*] --> 选择图片
选择图片 --> 压缩图片
压缩图片 --> 上传图片
上传图片 --> 返回URL
返回URL --> [*]
4. 旅行图
下面是整个上传头像的流程的旅行图:
journey
title 上传头像流程
section 选择图片
选择图片 --> 压缩图片 : 点击选择图片按钮