使用Volley StringRequest上传图片至服务器失败求助
Hey there! Let’s break down your problem and get that image upload working again. To answer your question directly: Yes, you’ll likely need to adjust either your Android StringRequest implementation (or both it and your PHP code), because StringRequest and SimpleMultipartRequest send data in completely different formats—and your new server’s encoding rules are highlighting that difference.
First, why the switch broke things
SimpleMultipartRequestautomatically uses themultipart/form-datacontent type, which is the standard for file uploads. PHP handles this format natively via the$_FILESsuperglobal, which is why it worked before.- A default
StringRequestsends data asapplication/x-www-form-urlencoded—this is for plain key-value pairs, not binary image data. Your PHP code is still expecting the multipart format, so it can’t parse the image from the StringRequest payload.
Fix 1: Adjust your Android StringRequest to send multipart data
You need to manually construct a multipart/form-data request body in your StringRequest, since it doesn’t do this by default. Here’s a working example:
String filepath = "your/image/file/path.jpg"; String UPLOAD_URL = "your/server/upload-endpoint.php"; StringRequest stringRequest = new StringRequest(Request.Method.POST, UPLOAD_URL, response -> { // Handle successful upload response Log.d("Upload", "Success: " + response); }, error -> { // Handle upload error Log.e("Upload", "Failed: " + error.getMessage()); }) { // Set the correct content type for multipart uploads @Override public String getBodyContentType() { return "multipart/form-data; boundary=----VolleyImageBoundary"; } // Build the multipart request body manually @Override public byte[] getBody() throws AuthFailureError { ByteArrayOutputStream bos = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(bos); String boundary = "----VolleyImageBoundary"; try { // Add the image part to the request dos.writeBytes("--" + boundary + "\r\n"); dos.writeBytes("Content-Disposition: form-data; name=\"image\"; filename=\"" + new File(filepath).getName() + "\"\r\n"); dos.writeBytes("Content-Type: image/jpeg\r\n\r\n"); // Read the image file into the request body FileInputStream fis = new FileInputStream(filepath); byte[] buffer = new byte[1024]; int bytesRead; while ((bytesRead = fis.read(buffer)) != -1) { dos.write(buffer, 0, bytesRead); } fis.close(); // End the multipart request dos.writeBytes("\r\n--" + boundary + "--\r\n"); return bos.toByteArray(); } catch (IOException e) { e.printStackTrace(); return null; } } }; // Add the request to Volley's queue Volley.newRequestQueue(this).add(stringRequest);
Fix 2: Verify your PHP code (and server config)
If your PHP code worked with SimpleMultipartRequest, it should work with the adjusted StringRequest above—since both send multipart/form-data. Double-check these things though:
- Ensure your PHP code is still using
$_FILESto access the uploaded image, like this:
<?php $uploadDir = "uploads/"; // Create upload directory if it doesn't exist if (!file_exists($uploadDir)) { mkdir($uploadDir, 0777, true); } if ($_FILES['image']['error'] === UPLOAD_ERR_OK) { $targetFile = $uploadDir . basename($_FILES["image"]["name"]); if (move_uploaded_file($_FILES["image"]["tmp_name"], $targetFile)) { echo "Image uploaded successfully"; } else { echo "Failed to move uploaded file"; } } else { echo "Upload error: " . $_FILES['image']['error']; } ?>
- Check your new server’s PHP configuration:
- Make sure
upload_max_filesizeandpost_max_sizeinphp.iniare set large enough for your images. - Confirm that file uploads are enabled (
file_uploads = On).
- Make sure
Key Takeaway
The core issue is that StringRequest doesn’t handle multipart uploads out of the box. By manually constructing the multipart request body on the Android side, you’re mimicking the behavior of SimpleMultipartRequest—so your existing PHP code should work, provided your new server’s config allows file uploads.
内容的提问来源于stack exchange,提问作者user9605882

