我要求将docx / pdf文件作为电子邮件发送。所以我将文件作为二进制字符串从ajax发送到Java Servlet&将其转换为InputStream&然后将它作为ByteArray传递给ByteArrayDataSource。我收到附件的电子邮件,但pdf文件为空。以下是代码: -
Ajax:
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 :(得分:0)
我找到了解决方案。而不是使用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);