Android Studio 在尝试上传时损坏了 Base64 字符串

Android Studio Corrupts Base64 String When Trying To Upload

所以我正在测试将图像上传到 php 服务器的方法。其中一种方法是将图像转换为 Base64 字符串并上传,然后在需要时对其进行解码。

当我上传图片时,我注意到字符串有所不同。 一些空格丢失,一些下一行放错了地方

在我将字符串发送到服务器之前,字符串没问题,然后它通过 php 文件中的 _POST 命令,然后使用 [=15= 将其插入数据库].

我怀疑我使用的 header 在我尝试上传时更改了字符串。 header 是 /x-www-form-urlencoded。我尝试使用 /json 但如果 json object 转换为字符串,它会更改原始字符串。那么我需要使用什么 header 才能使字符串不变?或者 还有其他方法可以将图片上传到 MySQL 数据库吗?

这是我上传字符串到服务器的方法:

ImageString = getStringImage(bitmap); 
String ImageUploadString="image="+ImageString; 
final OkHttpClient client = new OkHttpClient(); 
MediaType contentType = MediaType.parse("application/x-www-form-urlencoded; charset=utf-8"); 

RequestBody body = RequestBody.create(contentType, imageUploadString)); 
Request request = new Request.Builder().url(uploadURL).post(body).build(); 
Response response = null; 
try { 
    response = client.newCall(request).execute(); 
} catch (IOException e) { 
    e.printStackTrace(); 
} 
try { 
    String json = response.body().string(); 
} catch (IOException e) { 
    e.printStackTrace(); 
}

编辑:这是我用来插入图片的php文件:

<?php
$response = array();
if (isset($_POST['image']))
{
$image = $_POST['image'];
require_once __DIR__ . '/db_connect.php';
$db = new DB_CONNECT();
$result = $db->query("INSERT INTO images(image) VALUES('$image')");
if ($result) {
$response["success"] = 1;
$response["message"] = "Product successfully created.";
echo json_encode($response);
} else {
$response["success"] = 0;
$response["message"] = "Oops! An error occurred.";
echo json_encode($response);
}
} else {
$response["success"] = 0;
$response["message"] = "missing fields";
echo json_encode($response);
}
?>

问题是,您发送到服务器的数据正被您的HttpClient以某种方式编码。

你只需要用 php 代码解码它 -

举个例子,

我在这里向服务器发送设备ID,看看我是怎么做的url解码 -

if(isset($_POST['device_id']) && !empty($_POST['device_id']))
    $data->device_id = urldecode($_POST['device_id']);

对于图片上传,您始终可以进行分段上传,而不是将其转换为 base64。如果您使用改造,实施起来会更容易。

我正在添加 php 和 android 代码来执行此操作。我假设您使用的是 httpurlconnection 而不是改造。

PHP

  <?php
            $target_dir = "uploads/";
            $target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
            $uploadOk = 1;
            $imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
            // Check if image file is a actual image or fake image
            if(isset($_POST["submit"])) {
                $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
                if($check !== false) {
                    echo "File is an image - " . $check["mime"] . ".";
                    $uploadOk = 1;
                } else {
                    echo "File is not an image.";
                    $uploadOk = 0;
                }
            }
            // Check if file already exists
            if (file_exists($target_file)) {
                echo "Sorry, file already exists.";
                $uploadOk = 0;
            }
            // Check file size
            if ($_FILES["fileToUpload"]["size"] > 500000) {
                echo "Sorry, your file is too large.";
                $uploadOk = 0;
            }
            // Allow certain file formats
            if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
            && $imageFileType != "gif" ) {
                echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
                $uploadOk = 0;
            }
            // Check if $uploadOk is set to 0 by an error
            if ($uploadOk == 0) {
                echo "Sorry, your file was not uploaded.";
            // if everything is ok, try to upload file
            } else {
                if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
                    echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
                } else {
                    echo "Sorry, there was an error uploading your file.";
                }
            }
            ?>

Android

fileInputStream = new FileInputStream(new File(_filePath));

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

        // Allow Inputs & Outputs
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setUseCaches(false);

        // Enable POST method
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type",
                "multipart/form-data;boundary=" + boundary);
        outputStream = new DataOutputStream(
                connection.getOutputStream());
        outputStream.writeBytes(twoHyphens + boundary + lineEnd);
        outputStream
                .writeBytes("Content-Disposition: form-data; name=\"fileToUpload\";filename=\""
                        + _filePath + "\"" + lineEnd);
        outputStream.writeBytes(lineEnd);

        bytesAvailable = fileInputStream.available();
        bufferSize = Math.min(bytesAvailable, maxBufferSize);
        buffer = new byte[bufferSize];

        // Read file
        bytesRead = fileInputStream.read(buffer, 0, bufferSize);
        // int contentLength = bytesAvailable+
        // header.getBytes().length+footer.getBytes().length;

        while (bytesRead > 0) {
            outputStream.write(buffer, 0, bufferSize);

            bytesAvailable = fileInputStream.available();
            bufferSize = Math.min(bytesAvailable, maxBufferSize);
            bytesRead = fileInputStream.read(buffer, 0, bufferSize);
        }

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

我还建议您使用 retrofit,因为很多网络处理都是由库本身完成的。