【问题标题】:Sending Image by file in Android (with FileInputStream) to PHP and saving mysql by Blob在Android中通过文件(使用FileInputStream)将图像发送到PHP并通过Blob保存mysql
【发布时间】:2019-03-23 14:03:42
【问题描述】:
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 并像往常一样保存其他字段,但图像没有像使用 java NetBeans 那样保存在 blob 字段中。

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 并像往常一样保存其他字段,但图像没有像使用 java NetBeans 那样保存在 blob 字段中。

【问题讨论】:

    标签: php android mysql blob


    【解决方案1】:
    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();
            }
    

    【讨论】:

      【解决方案2】:

      我想您正试图通过调用json.put("imagemFIS", tag.getFis()); 将图像放入 json 中。

      它只是将FileInputStream 对象写入json。 您可能应该尝试将图像读取到 byte[],将其转换为 Base64 编码的 String,然后将其放入您的 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 或原样保存。

      希望有帮助!

      【讨论】:

      • 我已经知道如何使用 JAVA 前端/后端保存图像。但我的后端是 PHP(在远程服务器和数据库中),所以我试图将我的文件输入流发送到 PHP 并使用 php 保存在 DB blob 字段中
      • 我明白这一点,但FileInputStream 只包含FileDescriptor,它在您的后端不会有太大用处(除此之外,您必须以某种方式反序列化它),这就是您需要的原因从中获取一个,即 Base64 编码的字符串。在您的后端,您可以使用 base64_decode 将字符串解码为可以保存到数据库的字节数组。
      • 所以你的提示是将转换为base64的图像发送到我的php后端,将base64转换为我可以保存到我的db blob中的东西?这是?
      • @Kylukz 是的,你是对的。或者你也可以尝试将base64解码的图片保存到一个文件中,并将其路径或id保存在数据库中。
      • 我更喜欢将我的android应用程序发送的图像base64转换到我的php服务器,编码这个图像并像blob一样保存,因为我的桌面软件已经这样创建了;按 blob 保存
      【解决方案3】:
      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();
              }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-08-13
        • 1970-01-01
        • 2019-01-13
        • 2015-10-27
        • 2017-05-22
        • 2017-10-02
        • 2015-02-17
        • 1970-01-01
        相关资源
        最近更新 更多