You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Volley StringRequest上传图片至服务器失败求助

解决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

  • SimpleMultipartRequest automatically uses the multipart/form-data content type, which is the standard for file uploads. PHP handles this format natively via the $_FILES superglobal, which is why it worked before.
  • A default StringRequest sends data as application/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:

  1. Ensure your PHP code is still using $_FILES to 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'];
}
?>
  1. Check your new server’s PHP configuration:
    • Make sure upload_max_filesize and post_max_size in php.ini are set large enough for your images.
    • Confirm that file uploads are enabled (file_uploads = On).

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 08:19:19