Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Multi File Upload

Status
Not open for further replies.

fixthebug2003

Programmer
Oct 20, 2003
294
US
Hi,
We are having a web-based intranet application developed using Java, JSP, EJB on the server side and the clint-side, which is completely separated from the Server uses XML, JavaScript, HTML etc..and Oracle Database.

Can Someone suggest the best way to do a Multi-File upload to the database. I have used SA-fileup in the past but that was under microsoft Technology with IIS..!

Fixthebug2003
 
How do you get the file names to upload ?
Where are the files - client or server ?
 
Sedj,
Files are at the client machine. The user would pick one or more files and upload it to the server...the server can then store it to the database .

What I need is the technology to upload multiple files from Client to Server? SA-Fileup is one way ..but I guess it works with Microsoft Tecgnology as they have Active X Controls that can download on clients machine and accept multiple files..!

But how do we do it in a Java Environment?

Fixthebug2003
 
The only way I know how to do multiple files using Java is using a Java Applet, but due to security defaults an applet cannot access the user's HDD without it being a signed applet, which brings its own set of problems ...
 
Encountered this a while ago - here's the code from a test of mine.

You will need Apache Commons to us org.apache.commons.fileupload.* (available from the apache.org site)

In a web form change form tag to include enctype:

<form enctype="multipart/form-data" action="UploadTest2" method="post">

and include a number of
<input name="userfile" type="file"/>

Then use something like this (please excuse the messy code and unnecessary junk - no time atm to remove it and I'm afraid it was very early in the morning when i played with this!)

This stores the file as a file on the drive and then links to it - i'm sure u can convert the file to bytes though and store it directly as a sql blog. see the Apache Commons instructions (pretty good from memory)

Any problems get back to me

Cheers!


Relisys


Code:
import javax.servlet.*;
import javax.servlet.ServletInputStream;
import javax.servlet.ServletInputStream.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
import java.util.zip.*;
import org.w3c.dom.*;
import javax.xml.parsers.*;
import org.apache.commons.fileupload.*;
import java.text.*;



public class UploadTest2 extends AbstractPage {

 
    
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,IOException {
        doRequest(request, response);
    }
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,IOException {
        doRequest(request, response);
    }
    public void doRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException,IOException {
        
[COLOR=red]     
        
// Check that we have a file upload request
    System.err.println("Testing multipart request");        
    boolean isMultipart = FileUpload.isMultipartContent(request);        
[/color]    
    if (!isMultipart == true ) {
        AbstractItem[] outItems = {};
        Document outDOM = this.createDom(outItems, "", "");
        MyXSLProc xslProc = new MyXSLProc();
        xslProc.process(request, response, "UploadTest2.xsl", outDOM);
    return;
    }
[COLOR=red]
 System.err.println("Message is multipart");      
    // Create a new file upload handler
    DiskFileUpload upload = new DiskFileUpload();

    // Parse the request
    try {
        List items = upload.parseRequest(request);    
    

    // Set upload parameters
    upload.setSizeThreshold(0);  //All files more than 0 bytes are written direct to disk
    upload.setSizeMax(-1);       //-1 = there is no maximum size for files being uploaded
    upload.setRepositoryPath("../../../docs/");

    // Process the uploaded items one by one
    Iterator iter = items.iterator();
    while (iter.hasNext()) {
        FileItem item = (FileItem) iter.next();

        if (item.isFormField()) {
            boolean formChecker = processFormField(item);
 [/color]        
        } 
       }  
      }
    }
    catch(Exception e) {
        System.err.println("Error Parsing Request: "+e);
    }
    
// ALL CORRECT PROCESSING FINISHED - LOAD HTML PAGE    

    AbstractItem[] outItems = {};
    String reason = ("File has been saved.");
    Document outDOM = createDom(outItems, "", reason);
    MyXSLProc xslProc = new MyXSLProc();
    xslProc.process(request, response, "UploadTest2.xsl", outDOM);
    return;
    
    }
[COLOR=red]    
    public boolean processFormField(FileItem item){
        field ++;
        String name = item.getFieldName();
        String value = item.getString();
[/color]
        System.err.println("Found Form Field for Upload: ("+name+", "+value+")");
        if (name.equals("filename")) {
            docTitle = value;
        return true;
        } 
        if (name.equals("synopsis")) {
            synopsis = value;
        return true;
        }
        if (name.equals("category") && value == "new") {
            newCat = true;
            System.err.println("A new category has been selected");
        return true;
        }
        if (name.equals("catName") && value.equals("") && newCat == true) {
            System.err.println("Error Category Check #1");    
            return false;
            }
        if (name.equals("catName") && !value.equals("") && newCat == true) {

// SAVE NEW CATEGORY TO DATABASE            
            System.err.println("Error Category Check #2");
            con = getConnection();
            newCatID = Category.saveCategory(value, con);
            return true;
            }     
            
        if (name.equals("category") && !value.equals("Please Select")) {
            catID = Integer.parseInt(value);
            System.err.println("catID set to "+catID);
        return true;
        }
        if (name.equals("category") && value.equals("Please Select")){ 
            catIDcheck = false;
            return false;
        }
        if (name.equals("group") && !value.equals("Please Select")) {
            gID = Integer.parseInt(value);
            System.err.println("catID set to "+gID);
        return true;
        }  
        if (name.equals("group") && value.equals("Please Select")) { 
            gIDcheck = false;
            return false;
        }
        if (name.equals("public")) {
            isPublic = value;
            if (isPublic.equals("on")){
                isPublicInt = 1;
            }else {
                isPublicInt = 0;
            }
        return true;
        }
        return false;
    }
  [COLOR=red]      
    public boolean processUploadedFile(FileItem item){
 
        String fileName = item.getName();
        sizeInBytes = item.getSize();
        
        StringTokenizer tok = new StringTokenizer(fileName, "\\");
        int count = tok.countTokens();
        for (int i = 1; i < count ; i++) {
            tok.nextToken();
        }
        fileNameOnly = tok.nextToken();
        
        System.err.println("processing file upload: "+fileNameOnly);
         File uploadedFile = new File("../../../docs/"+fileNameOnly);
         if (!uploadedFile.exists()){
                        
             try {
// UPLOAD FILE 
                 item.write(uploadedFile);
[/color]
                System.err.println("Uploading the file "+fileNameOnly+" has been successful");
                
// CREATE ZIP VERSION OF THE FILE:
                
                // These are the files to include in the ZIP file 
                //String[] filenames = new String[]{"filename1", "filename2"}; 

                // Create a buffer for reading the files 
                byte[] buf = new byte[((int)sizeInBytes)+1]; 

                try { 
                // Create the ZIP file 
                String pathCheck = uploadedFile.getAbsolutePath();
                System.err.println(pathCheck+" Path check");
                String outFilename = "../../../impactdev/docs/"+fileNameOnly+".zip";
                String inFilename = "C:\\impactdev\\docs\\"+fileNameOnly;
                System.err.println("Attempting to Zip file: "+inFilename);
                ZipOutputStream out = new ZipOutputStream(new FileOutputStream(outFilename)); 

                // Compress the files 

                FileInputStream in = new FileInputStream(inFilename); 

                // Add ZIP entry to output stream. 
                out.putNextEntry(new ZipEntry(inFilename)); 

                // Transfer bytes from the file to the ZIP file 
                int len; 
                while ((len = in.read(buf)) > 0) { 
                out.write(buf, 0, len); 
                } 

                // Complete the entry 
                out.closeEntry(); 
                in.close(); 


                // Complete the ZIP file 
                out.close(); 
                
                } catch (IOException e) { 
                } 

//***************** SAVE DOCUMENT DETAILS TO DATABASE  *******************//

                con = getConnection();
                LibraryDoc.saveDocument(gID, docTitle, synopsis, fileNameOnly, catID, this.getFormattedDate(), isPublicInt, fileNameOnly+".zip", con);
             
   }

       
       
    
    //creates nodes for the XML document.
    public Document createDom(AbstractItem[] inItem, String title, String reason) throws ServletException {
        Document doc = null;
        try {
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder docBuilder = dbf.newDocumentBuilder();
            doc = docBuilder.newDocument();
        }
        catch(Exception e) {
            throw new ServletException(e.toString());
        }
        Element root = doc.createElement("page");
        doc.appendChild(root);
        Element titleElement = doc.createElement("title");
        titleElement.appendChild(doc.createTextNode(title));
        root.appendChild(titleElement);
        Element menuEl = doc.createElement("menu");
        Element loginEl = doc.createElement("login");
        Element mainpageEl = doc.createElement("mainpage");

        root.appendChild(menuEl);
        root.appendChild(loginEl);
        root.appendChild(mainpageEl);

        Element reasonEl = doc.createElement("reason");
        reasonEl.appendChild(doc.createTextNode(reason));
        root.appendChild(reasonEl);
        return doc;
    }
    
    public String getFormattedDate() {
        Date today;
        String dateOutFormatted;
        SimpleDateFormat formatter;
        formatter = new SimpleDateFormat("yyyy-MM-dd");
        today = new Date();
        dateOutFormatted = formatter.format(today);
        System.err.println("######## "+dateOutFormatted);
        return dateOutFormatted;
    }
}

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top