|
| 1 | +import java.io.File; |
| 2 | +import java.io.IOException; |
| 3 | +import java.util.List; |
| 4 | + |
| 5 | +import javax.servlet.ServletException; |
| 6 | +import javax.servlet.http.HttpServlet; |
| 7 | +import javax.servlet.http.HttpServletRequest; |
| 8 | +import javax.servlet.http.HttpServletResponse; |
| 9 | + |
| 10 | +import org.apache.commons.fileupload.FileItem; |
| 11 | +import org.apache.commons.fileupload.disk.DiskFileItemFactory; |
| 12 | +import org.apache.commons.fileupload.servlet.ServletFileUpload; |
| 13 | + |
| 14 | +public class FileManagement extends HttpServlet { |
| 15 | + private static final long serialVersionUID = 1L; |
| 16 | + |
| 17 | + public FileManagement() { |
| 18 | + super(); |
| 19 | + } |
| 20 | + |
| 21 | + protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { |
| 22 | + if(ServletFileUpload.isMultipartContent(request)){ |
| 23 | + try { |
| 24 | + List <FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request); |
| 25 | + for(FileItem item : multiparts){ |
| 26 | + if(!item.isFormField()){ |
| 27 | + String name = new File(item.getName()).getName(); |
| 28 | + //FIXME: change path to your path |
| 29 | + item.write( new File("path/to/save/uploaded/file" + File.separator + name)); |
| 30 | + } |
| 31 | + } |
| 32 | + //File uploaded successfully |
| 33 | + request.setAttribute("message", "Success!!!"); |
| 34 | + } catch (Exception ex) { |
| 35 | + request.setAttribute("message", "Oops: something went wrong " + ex); |
| 36 | + } |
| 37 | + }else{ |
| 38 | + |
| 39 | + request.setAttribute("message","No File found"); |
| 40 | + } |
| 41 | + request.getRequestDispatcher("/result.jsp").forward(request, response); |
| 42 | + |
| 43 | + } |
| 44 | + |
| 45 | + |
| 46 | +} |
0 commit comments