Servlet on gae delevering a jpeg image
I wish to write a servlet to run in GAE . This servlet wants to upload a image and to send it to a email address . This is the code :
ServletFileUpload upload = new ServletFileUpload();
FileItemIterator iterator = upload.getItemIterator(request);
while (iterator.hasNext()) {
FileItemStream itemStream = iterator.next();
is = itemStream.openStream();
if (itemStream.isFormField()){
String fieldname = itemStream.getFieldName();
if (fieldname.equals("Destinatar")){
destination = Streams.asString(is);
};
if (fieldname.equals("Mesaj")) {
message = Streams.asString(is);
};
if (fieldname.equals("Subject")) {
Subject = Streams.asString(is);
};
} else {
filename = FilenameUtils.ge开发者_如何转开发tName(itemStream.getName());
contentFile = Streams.asString(is);
}
}
..........
............
...........
MimeBodyPart attachment = new MimeBodyPart();
attachment.setFileName(filename);
ds = new ByteArrayDataSource(contentFile.getBytes() , "image/jpeg");
attachment.setDataHandler(new DataHandler(ds));
multipart.addBodyPart(attachment);
..............
Destination mailbox receives jpeg image -filename and dimension is right , like on the client- but browser can not understand the content ,it not recognize like a jpeg image. Do you have any ideea what's the problem? Thanks, Aurel
You are transforming a stream of binary data into a String at the line
contentFile = Streams.asString(is);
Don't do this. This transformation uses a charset and decodes bytes into chars, but certainly fails because the stream doesn't hold valid characters of this charset. If it's binary, store it as binary (into a stream, or a byte array) :
InputStream fileContent;
// ...
else {
filename = FilenameUtils.getName(itemStream.getName());
fileContent = is;
}
// ...
ds = new ByteArrayDataSource(fileContent, "image/jpeg");
attachment.setDataHandler(new DataHandler(ds));
精彩评论