繁体   English   中英

将BinaryString转换为ByteArray-Java

[英]Convert BinaryString to ByteArray - Java

我需要将docx / pdf文件作为电子邮件发送。 所以我将文件作为二进制字符串从ajax发送到Java Servlet,并将其转换为InputStream,然后将其作为ByteArray传递给ByteArrayDataSource。 我收到带有附件的电子邮件,但pdf文件为空。 下面是代码:

阿贾克斯:

var reader = new FileReader();
            reader.onload = function () {
                $.ajax({
                    url: 'SendAttachments',
                    type: 'POST',
                    data: jQuery.param({positionApllied:"tester",
                        Name:"John",
                        fileName:"invoice.pdf",
                        fileType:"application/pdf",
                        attachment:reader.result}),
                    success: function(data, textStatus, jqXHR)
                    {},
                    error: function(jqXHR, textStatus, errorThrown)
                    {}
                })
            }
            reader.readAsBinaryString(file)

Java Servlet:

    String filecontent =  request.getParameter("attachment");
    InputStream stream = new ByteArrayInputStream(filecontent.getBytes("UTF-8"));

    byte[] bucket = new byte[32*1024]; 
    ByteArrayOutputStream result = null; 
    try  {
      try {
        result = new ByteArrayOutputStream(bucket.length);
        int bytesRead = 0;
        while(bytesRead != -1){
          bytesRead = stream.read(bucket);
          if(bytesRead > 0){
            result.write(bucket, 0, bytesRead);
          }
        }
      }
      finally {
          stream.close();
      }
    }
    catch (IOException ex){
    }


    ByteArrayDataSource source = new ByteArrayDataSource(result.toByteArray(), fileMime);

我找到了解决方案。 代替使用reader.readAsBinaryString(file),而使用reader.readAsDataURL(file)。 并将参数传递为

data: jQuery.param({positionApllied:applied,
                        cName:cname,
                        fileName:fname,
                        fileType:ftype,
                        attachment:reader.result.split(",")[1]}),

在Java中,解码字符串。

String filecontent =  request.getParameter("attachment");

    byte[] decodedBytes = Base64.decode(filecontent);

    InputStream stream = new ByteArrayInputStream(decodedBytes);

    byte[] bucket = new byte[32*1024]; 
    ByteArrayOutputStream result = null; 
    try  {
      try {
        result = new ByteArrayOutputStream(bucket.length);
        int bytesRead = 0;
        while(bytesRead != -1){
          bytesRead = stream.read(bucket);
          if(bytesRead > 0){
            result.write(bucket, 0, bytesRead);
          }
        }
      }
      finally {
          stream.close();
      }
    }
    catch (IOException ex){
    }

    ByteArrayDataSource source = new ByteArrayDataSource(result.toByteArray(), fileMime);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM