2017-09-27 121 views
0

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

阿贾克斯:

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); 

回答

0

我已经找到了解决办法。而不是使用reader.readAsBinaryString(文件),请使用reader.readAsDataURL(文件)。并通过参数

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);