
Android
Javaimport Java.io.File;import Java.io.FileInputStream;import Java.io.IOException;import Java.io.OutputStream;import Java.net.HttpURLConnection;import Java.net.URL;public class FileUploader { public static void uploadFile(String serverUrl, String filePath) throws IOException { // 创建HTTP连接 URL url = new URL(serverUrl); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setRequestMethod("POST"); // 设置请求头 connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=<strong></strong>*"); // 构建请求体 File file = new File(filePath); FileInputStream fileInputStream = new FileInputStream(file); OutputStream outputStream = connection.getOutputStream(); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = fileInputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, bytesRead); } fileInputStream.close(); outputStream.close(); // 发送请求并获取响应 int responseCode = connection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { // 上传成功 // TODO: 处理服务器响应 } else { // 上传失败 // TODO: 处理上传失败的情况 } }}通过使用HTTP协议,我们可以在Android应用程序中实现文件上传到共享服务器托管的站点。本文介绍了文件上传的基本步骤,并提供了一个简单的案例代码来帮助你入门。希望本文对你理解Android文件上传有所帮助。Copyright © 2025 IZhiDa.com All Rights Reserved.
知答 版权所有 粤ICP备2023042255号