Отправка изображения по файлу в Android (с FileInputStream) в PHP и сохранение mysql с помощью Blob - PullRequest
0 голосов
/ 18 октября 2018
I'm trying to send an image converted by file and fileinputstream with my android app for my PHP server and then save it in BLOB field in MySQL DB, but I tried too many things, but nothing is ok. What can I do? And so, is this possible? Help, please!

Мой PHP-сервер получает JSON и сохраняет другие поля, как обычно, но изображение не сохраняется в поле BLOB-объектов, как я делаю с Java NetBeans.

public void cadastrarTAG(ModeloTAG tag) throws JSONException {

    FileWriter writeFile = null;

    JSONObject json = new JSONObject();

    json.put("tag", String.valueOf(tag.getTag()));
    json.put("equipamento", String.valueOf(tag.getEquipamento()));
    json.put("data_registro", String.valueOf(tag.getData_registro()));
    json.put("login", String.valueOf(tag.getLogin()));
    json.put("descricao", String.valueOf(tag.getDescricao()));
    json.put("obs", String.valueOf(tag.getObs()));
    json.put("total_manutencoes", 0);
    json.put("setor", String.valueOf(tag.getSetor()));
    json.put("imagemFileLength", tag.getFile().length()); Field file length
    json.put("imagemFIS", tag.getFis()); field fileinputstream


    try {
        writeFile = new FileWriter(new File(android.os.Environment.getExternalStorageDirectory(), "saida.json"));
        writeFile.write((json.toString()));
        writeFile.flush();
        writeFile.close();

    } catch(Exception e){
        System.err.println("ERRO-> "+e);
        //e.printStackTrace();
    }

    try {
        log.geraLog("Cadastro de TAG ("+tag.getSetor()+") (MOBILE)", "PINS", (String) Login.rotinas[1], md.getDataHora());
        enviaJson.enviaJsonGravar(arquivoPHP, json);
    } catch (Exception e) {
        e.printStackTrace();
    }

}

Мой PHP-сервер получаетJSON и сохраняет другие поля, как обычно, но изображение не сохраняется в поле BLOB-объектов, как я делаю с Java NetBeans.

Ответы [ 3 ]

0 голосов
/ 18 октября 2018

Полагаю, вы пытаетесь поместить изображение в json, вызывая json.put("imagemFIS", tag.getFis());.

Он просто записывает объект FileInputStream в json.Вам, вероятно, следует попробовать прочитать изображение в byte[], преобразовать его в String в кодировке Base64 и затем поместить в свой json.

Кроме того, может быть лучше сохранить путь к файлу изображения или URI какString в вашем ModeloTAG объекте, а не FileInputStream, то есть:

public void cadastrarTAG(ModeloTAG tag) throws JSONException {
    ...
    /* read bytes */
    try {
        final byte[] fileBytes = getFileBytes(new File(tag.getPath));
        json.put("image", Base64.encodeToString(fileBytes, Base64.DEFAULT));
    } catch (FileNotFoundException e) {
        // Handle the exception
    } catch (IOException e) {
        // Handle the exception
    }
    ...
}

private byte[] getFileBytes(final String path) throw IOException, FileNotFoundException {
    final FileInputStream fis = new FileInputStream(new File(path));
    final ByteArrayOutputStream bos = new ByteArrayOutputStream();

    final byte[] buffer = new byte[2048];

    int read = 0;

    while ((read = fis.read(buffer, 0, buffer.length)) > 0) {
        bos.write(buffer, 0, read);
    }

    fis.close();

    return bos.toByteArray();
}

И на вашем бэкэнде вам просто нужно декодировать строку в кодировке Base64 и сохранить ее как blob или как есть.

Надеюсь, это поможет!

0 голосов
/ 19 октября 2018
The problem is solved, I fix by sending imageview converted in Base64 for my PHP server and converting it into blob with this method.

public function salvaImagem($conn, $json, $cod) {
          $flag['code'] = 0;
            $blobData = base64_decode($json->{'imagem64'}); /* BASE64_DECODE and saving it like String with bind_param */
            $stmt = $conn->prepare("update tag set imagem = ? where id = ".$cod." and login = '{$json->{'login'}}'");
            $stmt->bind_param('s',  $blobData);
            $stmt->execute();

            if ($stmt->execute()) {
              echo "New record created successfully";
            } else {
              echo "Unable to create record";


            $stmt->close();
            $conn->close();
        }
0 голосов
/ 18 октября 2018
public function salvaImagem($conn, $json, $cod) {
          $flag['code'] = 0;
            echo "imagemFileLength 3 ---->>>>> ".$json->{'imagemFileLength'};
            echo "imagemFIS 3 ---->>>>> ".$json->{'imagemFIS'};

            $stmt = $conn->prepare("update tag set imagem = ? where id = ".$cod." and login = '{$json->{'login'}}'");
            $imageContent = fread($json->{'imagemFIS'}, filesize($json->{'imagemFileLength'}));
            //$imageContent = mysqli_real_escape_string($conn, $imageContent);
            //$stmt->bind_param('s',  mysql_real_escape_string($conn, $json->{'imagemFIS'}));
            $stmt->bind_param('s',  $imageContent);
            //$stmt->bindValue(1, $json->{'imagemFIS'});
            $stmt->execute();

            if ($stmt->execute()) {
              echo "New record created successfully";
            } else {
              echo "Unable to create record";


            $stmt->close();
            $conn->close();
        }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...