commons-user mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From "Schalk" <sch...@volume4.co.za>
Subject Re: commons-file upload
Date Wed, 05 Mar 2003 17:14:46 GMT
Have a look at the code below:

/**
 * uploadFile.java
 *
 * Created on December 11, 2002, 11:40 PM
 *
 *
 * @author  Design_DEMON
 * @version 1.0
 * Based on base classes from org.apache.commons.fileupload
 * Explenation of Strings:<br>
 * public String folder:: This string contains the information of your local
 * directory for testing your application locally.
 * <br>
 * public String tempFolder:: This is the location of your temp folder when
 * testing the application locally.
 * <br>
 * public String serverFolder:: Uncomment this line when transfering the
files
 * to the server. This is the complete string from the server root.
 * <br>
 * public String serverTemp:: Uncomment this line when transfering to the
server.
 * Tis should point to your temp directory on the server from the server
root.
 */

package volume4.sharelite.fileManager;

import java.io.*;
import java.util.*;
import java.lang.*;
import org.apache.commons.fileupload.*;
import java.net.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;


public class uploadFile extends HttpServlet {
    public String folder = "/Program Files/Apache Tomcat
4.0/webapps/PersonnelFinance/fileShare/fileExchange/files/";
    public String temp = "/temp";
    //public String serverFolder =
"/var/www/vhosts/personnelfinance/webapps/Persfin/fileShare/fileExchange/fil
es/";
    //public String serverTemp =
"/var/www/vhosts/personnelfinance/webapps/Persfin/temp/";
    public String DRIVER, URL, USER, PASS, recipient, fieldName, fieldData,
fileName, fileFieldName, comment, filePath;


    public void init() throws ServletException {
    ServletContext context = getServletContext();
    DRIVER = context.getInitParameter("DRIVER");
    URL = context.getInitParameter("PFURL");
    USER = context.getInitParameter("PFUSER");
    PASS = context.getInitParameter("PFPASS");
    }

    protected void processRequest(HttpServletRequest req,
HttpServletResponse res)
    throws ServletException, java.io.IOException {

        res.setContentType("text/html");
        PrintWriter out = res.getWriter();
        Connection con = null;

        try {

            FileUpload upload = new FileUpload();

            upload.setSizeMax(400000000);
            upload.setSizeThreshold(4096);
            upload.setRepositoryPath(temp);

            List items = upload.parseRequest(req);

            Iterator iter = items.iterator();
            while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();

            if (item.isFormField()) {

                fieldName = item.getFieldName();

                if(fieldName.equals("recipient")) {
                fieldData = item.getString();
                recipient = fieldData;
                }
                else if(fieldName.equals("comment")) {
                fieldName = item.getFieldName();
                fieldData = item.getString();
                comment = fieldData;
                }
                System.out.println("recipient: ");
                System.out.println(recipient);
                System.out.println("comment: ");
                System.out.println(comment);


            } else {

                if(item.getName().equals("")) {
                    System.out.println("forwarding");
                } else {


            fileName = item.getName();
            fileFieldName = item.getFieldName();

            StringTokenizer tokenizer = new StringTokenizer(fileName, "\\,
:, /");
            int amount = tokenizer.countTokens();
            for (int i = 0; i < amount -1; i++) {
                tokenizer.nextToken();
            }
            String currentFile = tokenizer.nextToken();
            filePath = folder + currentFile;

            item.getInputStream();
            item.write(folder + currentFile);

            item.delete();

            Class.forName(DRIVER);
            con = DriverManager.getConnection(URL,USER,PASS);
            PreparedStatement stmt = con.prepareStatement
            ("INSERT INTO fileexchange (fileName, fileURI, comments, toUser)
" +
            "VALUES (?, ?, ?, ?)"
            );

            stmt.setString(1, currentFile);
            stmt.setString(2, filePath);
            stmt.setString(3, comment);
            stmt.setString(4, recipient);

            int result = stmt.executeUpdate();
                }

        }
    }
res.sendRedirect("file_uploaded.jsp");

        }   catch(FileUploadException fue) {
         fue.printStackTrace();
         out.println("There was and error when reading and writing the file
to the server.");

        } catch(Exception e) {
            e.printStackTrace();
        }
}

    protected void doGet(HttpServletRequest req, HttpServletResponse res)
    throws ServletException, java.io.IOException {
        processRequest(req, res);
    }

    protected void doPost(HttpServletRequest req, HttpServletResponse res)
    throws ServletException, java.io.IOException {
        processRequest(req, res);
    }
}


Kind Regards »
Schalk Neethling »
Volume4.Development.Multimedia.Branding
.emotionalize.conceptualize.visualize.realize
Tel: +27125468436
Fax: +27125468436
email: schalk@volume4.co.za
url: www.volume4.co.za
----- Original Message -----
From: "Ip, Ting Shing" <TingShing.Ip@maniabarco.com>
To: <commons-user@jakarta.apache.org>
Sent: Wednesday, March 05, 2003 7:08 PM
Subject: commons-file upload


> Hello
>
> I have the follwing code with upload one file  to "d:\\test\\testfile".
> After the upload, i have opened  the file "d:\\test\\testfile". it was
> totally not the original file. It contains a string "upload". WHat is
wrong
> with mijn code.
>
>
>   public void doPost(HttpServletRequest request, HttpServletResponse
> response) throws ServletException, IOException {
>     response.setContentType(CONTENT_TYPE);
>     PrintWriter out = response.getWriter();
>
>       try {
>       ControllerResponse res = (ControllerResponse) request.getAttribute(
>                                   Controller.RESPONSE_KEY);
>
>       FileUpload fu = new FileUpload();
>       // maximum size before a FileUploadException will be thrown
>       fu.setSizeMax(999999999);
>       // maximum size that will be stored in memory
>       fu.setSizeThreshold(4096);
>       // the location for saving data that is larger than
getSizeThreshold()
>
>
fu.setRepositoryPath(Setup.getValueRequired(super.getDBName(request),
>                                                     "TempDir"));
>
>       List fileItems = fu.parseRequest(request);
>       // assume we know there are two files. The first file is a small
>       // text file, the second is unknown and is written to a file on
>       // the server
>       Iterator i = fileItems.iterator();
>
>       FileItem fi;
>       String fileName;
>       File file;
>       // write the file
>       out.println("<html>");
>       out.println("<head><title>FileUpload</title></head>");
>       out.println("<body>");
>       out.println("<p>The servlet has received a POST. This is the
> reply.</p>");
>       while(i.hasNext()){
>         fi = (FileItem)i.next();
>         fileName = fi.getName();
>         //file = new File(fileName);
>         fi.write("d:\\test\\testfile);
>         out.println("<p>Uploading file:  " + fileName +"<p>");
>       }
>       out.println("<p>The servlet has received a POST. This is the
> reply.</p>");
>       out.println("</body></html>");
>       out.flush();
>     } catch(DBException dbe) {
>       throw new ServletException("Tempory directory has not been defined
in
> the SETUP table", dbe);
>     } catch (Exception fue) {
>       throw new ServletException( fue);
>     }
>
>   }
> - - - - - - - - DISCLAIMER - - - - - - - -
> Unless indicated otherwise, the information contained in this message is
> privileged and confidential, and is intended only for the use of the
> addressee(s) named above and others who have been specifically authorized
to
> receive it. If you are not the intended recipient, you are hereby notified
> that any dissemination, distribution or copying of this message and/or
> attachments is strictly prohibited. The company accepts no liability for
any
> damage caused by any virus transmitted by this email. Furthermore, the
> company does not warrant a proper and complete transmission of this
> information, nor does it accept liability for any delays. If you have
> received this message in error, please contact the sender and delete the
> message. Thank you.
>



Mime
View raw message