permaculture playing cards
The moose likes Servlets and the fly likes attaching file from the form to an email Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Servlets
Bookmark "attaching file from the form to an email" Watch "attaching file from the form to an email" New topic

attaching file from the form to an email

Mary Wallace
Ranch Hand

Joined: Aug 25, 2003
Posts: 138
I am using jakarata fileupload to upload the file to a servlet. after that i need to send that as an email with the file attachments.
My que is how to get the DataSource from the fileuploaded?
Gowrishankar Mudaliar
Ranch Hand

Joined: Oct 20, 2001
Posts: 39
You might have to exetend the datasource into bytearraydatasource.
Thats how i did it. Check this link for reference
Hope this helps
Gareth Western
Ranch Hand

Joined: Apr 07, 2004
Posts: 45
Well, I guess what you need to do is get the file from the upload and then create an email and add attachments using the Java Activation Framework (JAF) (mail.jar).
To get the uploaded file and create a temporary file on the server (where the servlet is running):
try {
DiskFileUpload upload = new DiskFileUpload();

// Just set some system values, such as max upload size of a file and where to store the temp files

List items = upload.parseRequest(httpRequest);
Iterator x = items.iterator();
while (x.hasNext()) {
FileItem item = (FileItem)
// the list of items will have all form data in it (both form fields and the uploaded file(s)
if (!item.isFormField()) {
// if the item isn't a field (ie it's a file) then...
upFile = new File(item.getName());
// create a temp file
try {
} catch (Exception e) {
os.println("Caught Exception while writing upload file! "+e.toString());
} else {
// Item is a form field
// This does nothing, but you could make some custom behaviour?
}catch (FileUploadException e) {
os.println("Caught a FileUploadException!");
Then, using JAF, create a new DataHandler object based on your temp file
DataHandler foo = new DataHandler(new FileDataSource(upFile));
and add that to your email. I can't remember the exact syntax for doing this right now, but there are plenty of tutorials on the Sun website under the JAF section.
I hope that helps a bit!
PS: JAF Homepage is
Mary Wallace
Ranch Hand

Joined: Aug 25, 2003
Posts: 138
Thanks everyone. The way to do that is use ByteArrayDataSource class as GowriShanker suggested.
I agree. Here's the link:
subject: attaching file from the form to an email
It's not a secret anymore!