Solved

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

Posted on 2007-03-18
7
843 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
Gigs: Get Your Project Delivered by an Expert

Select from freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely and get projects done right.

 
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

Courses: Start Training Online With Pros, Today

Brush up on the basics or master the advanced techniques required to earn essential industry certifications, with Courses. Enroll in a course and start learning today. Training topics range from Android App Dev to the Xen Virtualization Platform.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
JDeveloper 12c for 32 bit 4 84
Where to store the queries for modification of table 4 62
fibonacci ten numbers 4 38
Why my table column Id is not passed to java object? 4 39
Java Flight Recorder and Java Mission Control together create a complete tool chain to continuously collect low level and detailed runtime information enabling after-the-fact incident analysis. Java Flight Recorder is a profiling and event collectio…
In this post we will learn how to connect and configure Android Device (Smartphone etc.) with Android Studio. After that we will run a simple Hello World Program.
Viewers learn about the “while” loop and how to utilize it correctly in Java. Additionally, viewers begin exploring how to include conditional statements within a while loop and avoid an endless loop. Define While Loop: Basic Example: Explanatio…
Viewers will learn about the different types of variables in Java and how to declare them. Decide the type of variable desired: Put the keyword corresponding to the type of variable in front of the variable name: Use the equal sign to assign a v…

776 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