Solved

JSP Jakarta Commons FileUpload- how to save to a directory?

Posted on 2007-03-18
7
842 Views
Last Modified: 2013-11-23
I am using apache jakarta commons upload library and am having a small issue with it.  I check my formfields for the proper type and then extract it.  My question is how Do i upload or save the file that is specified in the form from the previous page?  I am looking for a solid code example not a link to a tutorial that gives me pseudocode.  Any help would be appreciated.  Thanks.
0
Comment
Question by:RalphMercurio
  • 4
  • 2
7 Comments
 
LVL 15

Expert Comment

by:Javatm
ID: 18745686
Create a servlet to handle the request. This code is the same that you can find on the tutorial of apache commons upload site:

      protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            
            String name = request.getParameter("user");
            System.out.println(name);
            
            // boolean isMultipart = ServletFileUpload.isMultipartContent(request);

            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);

            try {
                  List items = upload.parseRequest(request);
                  Iterator iter = items.iterator();

                  while (iter.hasNext()) {
                        FileItem item = (FileItem) iter.next();
                        String fileName = item.getName();
                        File theFile = new File(fileName);
                        if (item.isFormField()) {
                              File uploadedFile = new File("C:/YourFolder/"+ theFile.getName());
                              try {
                                    item.write(uploadedFile);
                                    insertToHibernate(name, uploadedFile.toString());
                                    redirectPage(request, response, uploadedFile
                                                .getAbsolutePath());
                              } catch (Exception e) {
                                    e.printStackTrace();
                              }
                        } else {
                              File uploadedFile = new File("C:/YourFolder/"+ theFile.getName());
                              try {
                                    item.write(uploadedFile);
                                    insertToHibernate(name, uploadedFile.toString());
                                    redirectPage(request, response, uploadedFile
                                                .getAbsolutePath());
                              } catch (Exception e) {
                                    e.printStackTrace();
                              }
                        }
                  }
            } catch (FileUploadException e1) {
                  // TODO Auto-generated catch block
                  e1.printStackTrace();
            }
      }
0
 
LVL 15

Expert Comment

by:Javatm
ID: 18745689
Remove this:
 insertToHibernate(name, uploadedFile.toString());
                                    redirectPage(request, response, uploadedFile
                                                .getAbsolutePath());
0
 
LVL 15

Expert Comment

by:Javatm
ID: 18745697
Don't forget to put the jar commons library on your path and import this together with the code above:
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
0
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
LVL 30

Expert Comment

by:Mayank S
ID: 18745722
We can't give complete working code without you coming up with some coding efforts of your own - its against site rules. Pls come up with some code and we will help you fix it if there are issues.
0
 

Author Comment

by:RalphMercurio
ID: 18745724
Here is my code:

for (int i = 0; i < fileItems.size(); i++) {
        FileItem fi = (FileItem) fileItems.get(i);
        if (!fi.isFormField() && "document".equals(fi.getFieldName())) {
            f.setFileLocation(fi.getName());
            fileInput = fi.getInputStream();
           
           
           
        } else if (fi.isFormField() && "User".equals(fi.getFieldName())) {
            a.setEmployeename(fi.getString());
        } else if (fi.isFormField() && "asset".equals(fi.getFieldName())) {
            a.setAsset(fi.getString());
            f.setAsset(fi.getString());
            n.setAsset(fi.getString());
        } else if (fi.isFormField() && "documenttype".equals(fi.getFieldName())) {
            f.setDocumentType(fi.getString());
        } else if (fi.isFormField() && "".equals(fi.getFieldName())) {

        } else if (fi.isFormField() && "ITUsers".equals(fi.getFieldName())) {
             f.setTechOpsEngineer(fi.getString());
        } else if (fi.isFormField() && "serial".equals(fi.getFieldName())) {
            a.setSerial(fi.getString());
        } else if (fi.isFormField() && "status".equals(fi.getFieldName())) {
            a.setStatus(fi.getString());
        } else if (fi.isFormField() && "notes".equals(fi.getFieldName())) {
            n.setNotes("{Assigned to " + a.getEmployeename() + " Status is now " + a.getStatus() + "} -- " + fi.getString());

        }
    }

Can I still do it with your code and if so which parts?
0
 
LVL 15

Accepted Solution

by:
Javatm earned 500 total points
ID: 18746117
In the while part:
while (iter.hasNext()) {
}
0
 

Author Comment

by:RalphMercurio
ID: 18855136
thanks
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Python Assistance 7 73
micro services vs rest web services 16 87
servlet  URL Rewriting 1 28
how to add new optional parameter to JSP 1 29
Java contains several comparison operators (e.g., <, <=, >, >=, ==, !=) that allow you to compare primitive values. However, these operators cannot be used to compare the contents of objects. Interface Comparable is used to allow objects of a cl…
Introduction This article is the first of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article explains our test automation goals. Then rationale is given for the tools we use to a…
This tutorial explains how to use the VisualVM tool for the Java platform application. This video goes into detail on the Threads, Sampler, and Profiler tabs.
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …

862 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

25 Experts available now in Live!

Get 1:1 Help Now