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