/**File Upload Servlet. Clients use a HTML form to send files to this servlet. * Internet Programming 2 - Course *@author Martin Carlsson */ import java.io.*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; import com.oreilly.servlet.MultipartRequest; import com.oreilly.servlet.ServletUtils; public class FormsFileUpload extends HttpServlet { public void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException { res.setContentType("text/plain"); ServletOutputStream out = res.getOutputStream(); File dir = (File)getServletContext().getAttribute("javax.servlet.context.tempdir"); MultipartRequest mR = new MultipartRequest(req, dir.getAbsolutePath() ,500000); Enumeration files = mR.getFileNames(); while(files.hasMoreElements()) { String name = (String)files.nextElement(); String filename = mR.getFilesystemName(name); String type = mR.getContentType(name); File file = mR.getFile(name); if(file == null) { out.println("No file selected, please try again!"); return; } if(!(type.equals("text/plain") || type.equals("image/gif") || type.equals("image/pjpeg") || type.equals("image/x-png") || type.equals("image/jpeg"))) { out.println("filename: "+filename); out.println("type: "+type); out.println("SIZE: "+file.length()); } else { try{ res.setContentType(type); String pathToFile = dir.getAbsolutePath()+"\\"+filename; ServletUtils.returnFile(pathToFile, out); } catch (FileNotFoundException fNfE) { res.sendError(res.SC_NOT_FOUND); } catch(IOException iOe) { res.sendError(res.SC_INTERNAL_SERVER_ERROR, ServletUtils.getStackTraceAsString(iOe)); } } // else } // while } // doPost } // End class FormsFileUpload