Android 和服务器之间的文件上传是 Android 开发中比较常见的操作。本文将介绍几种用于将文件上传到服务器的技术,并提供使用这些技术的示例代码。
一、使用 HttpURLConnection
Java 标准库中的 HttpURLConnection 可以用于将文件上传到服务器。我们可以使用它将文件上传到远程服务器。
以下是使用 HttpURLConnection 进行文件上传的步骤:
URL url = new URL("http://example.com/upload.php"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 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="file";filename="" + fileName + """ + lineEnd); dos.writeBytes("Content-Type: " + mimeType + lineEnd); dos.writeBytes("Content-Transfer-Encoding: binary" + lineEnd); dos.writeBytes(lineEnd); byte[] buffer = new byte[8192]; int count; while ((count = fis.read(buffer)) > 0) { dos.write(buffer, 0, count); } dos.writeBytes(lineEnd);
其中,boundary 是分隔符,fileName 是文件名称,mimeType 是文件的类型(例如 image/png)。
fis.close(); dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd); dos.flush(); int responseCode = conn.getResponseCode(); String responseMessage = conn.getResponseMessage(); conn.disconnect();
完整的 HttpURLConnection 示例可以在以下链接中找到:
https://gist.github.com/GauthamGoli/8a1e138922e83d48946860dd18e5b37b
二、使用 Volley
Volley 是 Google 开发的一个 Android 应用程序网络库,可用于快速轻松地进行网络请求。Volley 可以帮助我们将文件上传到服务器。
以下是使用 Volley 进行文件上传的步骤:
RequestQueue queue = Volley.newRequestQueue(this);
StringRequest strReq = new StringRequest(Request.Method.POST, uploadUrl,
new Response.Listener