You are viewing a plain text version of this content. The canonical link for it is here.
Posted to user@commons.apache.org by "Ip, Ting Shing" <Ti...@maniabarco.com> on 2003/03/05 18:08:57 UTC

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.

Re: commons-file upload

Posted by Martin Cooper <ma...@apache.org>.
"Ip, Ting Shing" <Ti...@maniabarco.com> wrote in message
news:E78C42D5FF60D611AF870002A5ECEFEA5B87EB@mbgemex01.maniabarco.com...
> 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.

Firs, you say above that you are uploading one file, but the comments in
your code say that you are assuming two files. Second, you are not checking
the FileItem instances to see if they are actually files (as opposed to
other HTML form fields). Since you didn't post the page you are using to
submit the request, I can't tell whether that is the cause of the problem
you are seeing, or if it's something else.

In any case, I would strongly suggest that you refactor your code to cleanly
separate the request processing from the response generation. The way it is
now, it's not that easy to figure out just what you are trying to do.

--
Martin Cooper


>
>
>   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.
>




Re: commons-file upload

Posted by Martin Cooper <ma...@apache.org>.
PLEASE stop sending your sample servlet to the list each time a question
comes up on FileUpload. If you think it will be useful to people, then you
should post it on a web server somewhere, or just offer to provide it on
request. But please refrain from clogging up the list, and the archives,
with all these copies of the code itself.

Also, IMHO, in most cases, people will appreciate a direct response to their
questions more than a suggestion that they go read some other code to see if
that helps them solve their problem.

--
Martin Cooper


"Schalk" <sc...@volume4.co.za> wrote in message
news:000801c2e33a$b9485990$0100a8c0@ServerMAIN...
> 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" <Ti...@maniabarco.com>
> To: <co...@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.
> >




Re: commons-file upload

Posted by Schalk <sc...@volume4.co.za>.
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" <Ti...@maniabarco.com>
To: <co...@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.
>