How to send a non-local attachment with JavaMail
I'm building an application using jsp's, servlets, and all that fun stuff. Right now, I have a form that passes through all the information from the form to an html email that is sent using the JavaMail API. It works, but I am trying to send an attachment, and the way I have it set up right now does not work...
<div class="section">Upload Files: <开发者_开发问答;input id="fileUpload" type="file" /></div>
I take this input's value, pass it through to my servlet and try to send the email. The problem is that when the file is sending, the servlet cannot locate the file because this tag gives it the path
C:\fakepath\file.doc
Any help would be amazing.
I figured it out. The fakepath was a security feature in browsers. What happens though with tomcat is that the file is actually stored in a temp folder inside the tomcat folder. So i just had to play with a tomcat library, commons.fileupload, and i used that to pull the data from the file, regardless of the fakepath location.
//Handle File Upload for the attachment
ServletFileUpload servletFileUpload = new ServletFileUpload(new DiskFileItemFactory());
try{
List fileItemsList = servletFileUpload.parseRequest(request);
//TODO: Take datafile input from the field and pass the file name so that we can view the file name
Iterator it = fileItemsList.iterator();
while (it.hasNext()){
FileItem fileItem = (FileItem)it.next();
if (fileItem.isFormField()){
/* The file item contains a simple name-value pair of a form field */
}
else{ //do what you want with the file}
I then passed it through to my mail utility, changed the name of the file to the correct name to have the correct extension, and it worked. Of course, you have to encode the form as a multipart form, and you have to make the Mime Message multipart as well. But its fairly simple after all that.
MimeBodyPart textPart = new MimeBodyPart();
textPart.setContent(body, "text/html");
MimeBodyPart attachFilePart = new MimeBodyPart();
FileDataSource fds =
new FileDataSource(file);
attachFilePart.setDataHandler(new DataHandler(fds));
attachFilePart.setFileName(fileName);
Multipart mp = new MimeMultipart();
mp.addBodyPart(textPart);
mp.addBodyPart(attachFilePart);
精彩评论