Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / General / December 2006

Tip: Looking for answers? Try searching our database.

Naming an uploaded file without filepath

Thread view: 
jonesy <3 - 15 Dec 2006 02:10 GMT
I am using the Jakarta Commons FileUpload library to upload a file from
an Intranet site to a directory on the UNIX box.  This is working
correctly.

Except, when the file is transferred to the UNIX box, it is named with
the full file path from my local computer, rather than the original
file name
e.g.
I am uploading a file called spreadsheet.xls, which is located on my
desktop.  The file uploads correctly but is named "D:\Documents and
Settings\user\Desktop\spreadsheet.xls" when it should be called
"spreadsheet.xls"

Does anyone know how to fix this?

I have included my code below, I do not have much experience and have
followed examples to get the code working.. so I am unsure what part
should be edited.

Thanks and Regards,
Laura

/**
* doPost method.
*
* @param req, res  Servlet request and response
* @exception ServletException, IO Exception
* @return void
*/
   protected void doPost ( HttpServletRequest req, HttpServletResponse
res ) throws ServletException, IOException
   {
    PrintWriter out = res.getWriter();
    HttpSession session = req.getSession(true);
    session.setMaxInactiveInterval(1200);
    ServletContext context = getServletContext();

    // For testing whether the form has posted with mulitpart encoding
    boolean isMultipart = false;

    if(!"post".equals(req.getMethod().toLowerCase()))
    {
        isMultipart = false;
    }

    String contentType = req.getContentType();
    if(contentType == null)
    {
        isMultipart = false;
    }

    isMultipart = contentType.toLowerCase().startsWith("multipart/");

    // check if the http request is a multipart request,
    // in other words check that the http request can have uploaded files
    if (isMultipart)
    {
        //  Create a factory for disk-based file items
        FileItemFactory factory = new DiskFileItemFactory();

        //  Create a new file upload handler
        ServletFileUpload servletFileUpload = new ServletFileUpload(factory);

        // Set upload parameters
        // See Apache Commons FileUpload for more information
        // http://jakarta.apache.org/commons/fileupload/using.html
        servletFileUpload.setSizeMax(-1);

        try
             {
                   String directory = "";

                   // Parse the request
                   List items = servletFileUpload.parseRequest(req);

                   // Process the uploaded items
                   Iterator iter = items.iterator();

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

                // the param tag directory is sent as a request parameter to
                // the server
                // check if the upload directory is available
                if (item.isFormField())
                {
                    String name = item.getFieldName();

                   if (name.equalsIgnoreCase("directory"))
                   {
                    directory = item.getString();
                   }

               // retrieve the files
                }
                else
                {
                    // the fileNames are urlencoded
                           String fileName = URLDecoder.decode(item.getName());

                           File file = new File(directory, fileName);
                           file = new File(BASE_DIRECTORY, file.getPath());

                           // retrieve the parent file for creating the directories
                           File parentFile = file.getParentFile();

                           if (parentFile != null)
                           {
                               parentFile.mkdirs();
                           }

                          // writes the file to the filesystem
                           item.write(file);
                         }
                   }
             }
             catch (Exception e)
             {
                   e.printStackTrace();
                   res.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                   out.println("<font color=red>An Exception error
occurred.</font><br> Please try resubmitting the form later.");
             }
             res.setStatus(HttpServletResponse.SC_OK);

       }
      else
       {
        res.setStatus(HttpServletResponse.SC_BAD_REQUEST);
       }
}
Manish Pandit - 15 Dec 2006 19:22 GMT
I've had this problem for a long time. I tried the File API to get just
the file name, but it did not work out.

I had to do a quick and dirty (you can call it other names too!) hack
to fix it, which has no side effects as far as my system was concerned.
You might need to think about your requirements/system boundaries
before considering it.

On the file name, I did an indexOf("/") - if it was > 0, I knew it was
a unix path. I proceeded by tokenizing the path by "/", and putting the
elements in a stack. The element at the top was the file name I needed.
If the indexOf("/") is zero, I checked for indexOf("\") and did the
same process (stack it and get the top element).

You can try something similar and see if it works.

-cheers,
Manish


Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.