【问题标题】:java.io.utfdataformatexception: String is too longjava.io.utfdataformatexception:字符串太长
【发布时间】:2012-12-09 11:04:03
【问题描述】:

在将图像发送到 java 服务器时,我遇到了标题中的异常

代码如下:

       ByteArrayOutputStream stream = new ByteArrayOutputStream();
       img.compress(Bitmap.CompressFormat.PNG, 100, stream);
       byte[] byteArray = stream.toByteArray();

       String imageDataString = new String(Base64.encodeBase64(byteArray)); 
       System.out.println(imageDataString);

       dataOutputStream.writeUTF(imageDataString);
       dataOutputStream.flush();

img 是位图文件。

任何帮助将不胜感激!

【问题讨论】:

  • 它适用于较小的图像吗?你如何从字符串恢复服务器上的图像??
  • dataOutputStream 的类型是什么?
  • 图像没有被发送,因为根据异常解码字符串太长但是当我发送一些其他编码字符串时,比如`string = "some string" 它被发送
  • @kuznetsov 有一个将图像编码和解码为 base64 字符串的提示,我已经为小图像完成了它stackoverflow.com/questions/13785594/…
  • 它在任何 1kb 和更少的图像上都能成功吗?使用Strings发送图片的方式异常。

标签: java client-server utf


【解决方案1】:

@Sarram 遵循打击链接中的代码,我在soap请求中发送图像以及base64String形式的其他数据,我正在将其转换为文件

blow是代码的参考

Writing decoded base64 byte array as image file

我正在使用这个很酷的解码器import sun.misc.BASE64Decoder; 服务器端可以这样做

        String filePath = "/destination/temp/file_name.jpg";
        File imageFile = new File(filePath);
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(imageFile);//create file
        } catch (FileNotFoundException e1) {
            e1.printStackTrace();
        }
        BASE64Decoder decoder = new BASE64Decoder();//create decodeer object
        byte[] decodedBytes = null;
        try {
            decodedBytes = decoder.decodeBuffer(imageFileBase64);//decode base64 string that you are sending from clinet side 
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        try {
            fos.write(decodedBytes);//write the decoded string on file and you have ur image at server side
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            fos.flush();
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

【讨论】:

  • 你是从安卓模拟器的sd卡中获取图片吗?
  • 这里我将图像从客户端发送到服务器,所以我需要在 android 上对其进行编码并在 java 中的服务器上对其进行解码
  • 我在 android clinet 中从 SD 卡输入图像,然后我将其编码为 base64 字符串,我将该字符串放入肥皂调用请求中,并且在服务器端我正在解码它,上面是用于解码base 64 String中的图像并将其转换为文件的代码
猜你喜欢
  • 1970-01-01
  • 2019-11-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-16
相关资源
最近更新 更多