在 Android 中进行文件上传通常涉及到与服务器的交互,并且涉及到使用 HTTP 协议的 POST 请求。下面是一个简单的 Android 文件上传的示例,使用 HttpURLConnection 进行文件上传。

1. 添加网络权限:

在 AndroidManifest.xml 文件中添加网络权限:
<uses-permission android:name="android.permission.INTERNET" />

2. 实现文件上传的 AsyncTask:
import android.os.AsyncTask;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class FileUploadTask extends AsyncTask<String, Void, String> {

    @Override
    protected String doInBackground(String... params) {
        String targetUrl = params[0];
        String filePath = params[1];

        try {
            return uploadFile(targetUrl, filePath);
        } catch (Exception e) {
            return "Error: " + e.getMessage();
        }
    }

    private String uploadFile(String targetUrl, String filePath) throws Exception {
        String boundary = "*****";
        String lineEnd = "\r\n";
        String twoHyphens = "--";

        FileInputStream fileInputStream = null;
        DataOutputStream dataOutputStream = null;

        try {
            File file = new File(filePath);
            fileInputStream = new FileInputStream(file);

            URL url = new URL(targetUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            // 设置连接属性
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Connection", "Keep-Alive");
            connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);

            dataOutputStream = new DataOutputStream(connection.getOutputStream());
            dataOutputStream.writeBytes(twoHyphens + boundary + lineEnd);
            dataOutputStream.writeBytes("Content-Disposition: form-data; name=\"file\";filename=\"" + file.getName() + "\"" + lineEnd);
            dataOutputStream.writeBytes(lineEnd);

            // 将文件数据写入输出流
            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = fileInputStream.read(buffer)) != -1) {
                dataOutputStream.write(buffer, 0, bytesRead);
            }

            dataOutputStream.writeBytes(lineEnd);
            dataOutputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

            // 获取服务器响应
            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                // 读取服务器响应
                // ...
                return "File uploaded successfully";
            } else {
                return "File upload failed with response code: " + responseCode;
            }

        } finally {
            // 关闭流
            if (fileInputStream != null) {
                fileInputStream.close();
            }
            if (dataOutputStream != null) {
                dataOutputStream.flush();
                dataOutputStream.close();
            }
        }
    }

    @Override
    protected void onPostExecute(String result) {
        // 处理上传结果
        // result 包含服务器响应或错误消息
    }
}

3. 使用 AsyncTask 进行文件上传:
String targetUrl = "Your server URL here";
String filePath = "Path to your file here";

FileUploadTask fileUploadTask = new FileUploadTask();
fileUploadTask.execute(targetUrl, filePath);

请确保将 "Your server URL here" 替换为实际的服务器端接收文件上传的 URL,将 "Path to your file here" 替换为实际文件的路径。在服务器端,需要实现相应的接口来处理文件上传。

这个例子中使用了 HttpURLConnection 来执行文件上传,通过设置请求头和写入文件数据到输出流的方式完成文件上传。在实际应用中,你可能需要根据服务器端的要求调整请求头和请求体的格式。另外,为了避免在主线程执行网络操作,你可能需要在 doInBackground 方法中使用 runOnUiThread 或者使用 AsyncTask 的 onProgressUpdate 方法来更新 UI。


转载请注明出处:http://www.pingtaimeng.com/article/detail/15196/Android