尝试上传时,Android Studio会破坏Base64字符串

时间:2017-03-30 05:34:33

标签: php android base64

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

当我上传图片时,我注意到字符串存在差异。 有些空格丢失,而下一行则错位

在我将字符串发送到服务器之前,字符串是可以的,然后它在php文件中通过_POST命令,然后使用INSERT INTO将其插入数据库。

我怀疑我使用的标题会在我尝试上传时更改字符串。标题是/x-www-form-urlencoded。我尝试使用/json,但如果json对象转换为字符串,则会更改原始字符串。那么我需要使用什么标题,以便字符串不会改变?或是否有另一种方法可将图片上传到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);
}
?>

2 个答案:

答案 0 :(得分:0)

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

您只需要在php代码 -

中对其进行解码

例如,

这里我将设备ID发送到服务器,看看我是如何进行网址解码的 -

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

答案 1 :(得分:0)

对于图片上传,您始终可以进行多部分上传,而不是将其转换为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);

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