将图片从Android上传到PHP服务器可以通过以下步骤实现:
下面是每个步骤的详细解释:
Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, PICK_IMAGE_REQUEST);
Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
URL url = new URL("http://example.com/upload.php");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
OutputStream outputStream = connection.getOutputStream();
outputStream.write(imageBytes);
outputStream.flush();
outputStream.close();
$targetDir = "uploads/";
$targetFile = $targetDir . basename($_FILES["file"]["name"]);
move_uploaded_file($_FILES["file"]["tmp_name"], $targetFile);
这是一个基本的图片上传到PHP服务器的流程。根据具体需求,可以对代码进行适当的修改和扩展。
领取专属 10元无门槛券
手把手带您无忧上云