0

I'm trying to rename a file after upload but the error I get is:

File Upload Failed due to java.io.FileNotFoundException: C:\Users\Akhil\Documents\CryptographicSteganography\Image\toshaMon Dec 29 22:21:41 IST 2014.jpg (The filename, directory name, or volume label syntax is incorrect).

I went through almost all the possible related topics in stackoverflow as well as other sites but couldn't resolve this error.

my servlet class:

package FileUploadHandler;

import com.pointerunits.web.*;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FilenameUtils;

/**
 * Servlet implementation class FileUploadServlet
 */
public class FileUploadServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    Date date = new Date();
    String name = null;

    public String UPLOAD_DIRECTORY = "";
    /**
     * @see HttpServlet#HttpServlet()
     */

    public FileUploadServlet() {
        super();
        // TODO Auto-generated constructor stub
    }


    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
         //process only if its multipart content
        String FileType = (String)request.getSession().getAttribute("FileType");
        //System.out.println(FileType);

        String usrnam = (String) request.getSession().getAttribute("name");
        //System.out.println(usrnam);
        switch (FileType) {
            case "image":
                //UPLOAD_DIRECTORY = "C:/Users/Akhil/Downloads/SpringMain/SpringMain/WebContent/WEB-INF/Uploads/Image";
                UPLOAD_DIRECTORY = "C:/Users/Akhil/Documents/CryptographicSteganography/Image";
                break;


            case "audio":
                UPLOAD_DIRECTORY = "C:/Users/Akhil/Documents/CryptographicSteganography/Image";
                break;


            case "video":
                UPLOAD_DIRECTORY = "C:/Users/Akhil/Documents/CryptographicSteganography/Image";
                break;

        default:
            System.out.println("invalid path");
            break;
        }

        //UPLOAD_DIRECTORY = getServletContext().getRealPath(UPLOAD_DIRECTORY);
        //System.out.println(UPLOAD_DIRECTORY);
                if(ServletFileUpload.isMultipartContent(request)){

                    try {

                        List<FileItem> multiparts = new ServletFileUpload(

                                   new DiskFileItemFactory()).parseRequest(request);

                      // System.out.println(getName());
        String nam = usrnam+date.toString();
                        for(FileItem item : multiparts){

                            if(!item.isFormField()){
                                String name = item.getName();
                                //System.out.println(name);
                                File uploadedFile = new File(UPLOAD_DIRECTORY+File.separator+nam+name.substring(name.indexOf('.')));
                                item.write(uploadedFile);
                                //File uploadedFile = new File(UPLOAD_DIRECTORY, name);
                    // item.write( new File(UPLOAD_DIRECTORY + File.separator + nam + name));
                            //  System.out.println("uploaded file : "+uploadedFile.toString());

//                             System.out.println(nam);
//                             String f1 = uploadedFile.getAbsolutePath();
//                             System.out.println(f1);
//                             
//                             File oldName = new File(f1);
//                             //File newName = new File(UPLOAD_DIRECTORY+File.separator+nam+"."+FilenameUtils.getExtension(oldName.toString()));
//                             File newName = new File(UPLOAD_DIRECTORY,nam+name.substring(name.indexOf('.')));
//                              File uploadedFile = new File ("C:\\Users\\Akhil\\Documents\\CryptographicSteganography\\Image\\IMAG0187.jpg");
//                              File newName = new File("C:\\Users\\Akhil\\Documents\\CryptographicSteganography\\Image\\toshaMon Dec 29 22:01:40 IST 2014.jpg");
//                              boolean flag = uploadedFile.renameTo(newName);
//                             
//                             System.out.println(newName.toString());
//                             
////                               File uploadedFile = new File(UPLOAD_DIRECTORY , nam);   
////                               item.write(uploadedFile);
//                             


                            }

                        }

                        System.out.println();

                       //File uploaded successfully

                       request.setAttribute("message", "File Uploaded Successfully");

                    } catch (Exception ex) {

                       request.setAttribute("message", "File Upload Failed due to " + ex);

                    }         



                }else{

                    request.setAttribute("message",

                                         "Sorry this Servlet only handles file upload request");

                }



                request.getRequestDispatcher("/result.jsp").forward(request, response);

    }

}

below is the .jsp webpage:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Upload File</title>
</head>
<h1><%
    String FileType = request.getParameter("select");
    out.println("File Type is: "+FileType);
    session.setAttribute("FileType", FileType);
%>
</h1>
<body>
<body>

File:
<%if (FileType.equalsIgnoreCase("image")){%>

    <form method="POST" action="FileUploadServlet" enctype="multipart/form-data" >
    <input type="file" name="<%=session.getAttribute("FileType")%>" accept="image/*"> <br/>
    <input type="submit" value="Upload" name="upload" >
    </form>

<% }

else if (FileType.equalsIgnoreCase("audio")){%>

<form method="POST" action="FileUploadServlet" enctype="multipart/form-data" >
<input type="file" name="<%=session.getAttribute("FileType") %>" accept="audio/*" > <br/>
<input type="submit" value="Upload" name="upload" >
</form>
<% }

else if (FileType.equalsIgnoreCase("video")){%>

<form method="POST" action="FileUploadServlet" enctype="multipart/form-data" >
<input type="file" name="<%=session.getAttribute("FileType") %>" accept="video/*" > <br/>
<input type="submit" value="Upload" name="upload" >
</form>
<% }
%>

</body>
</body>
</html>

Sorry about that awful lot of comments: my program was going through a testing phase

trooper
  • 4,444
  • 5
  • 32
  • 32

1 Answers1

0

May be there is right issue, it cannot access the folder as it does not have right. If this is not the case then.

You should try to remove space from the file name format data value to a format that does not contains any space Sample Format Date . Because space can create problems.

Before item.write(uploadedFile); check

if(!uploadedFile.exists()){
  uploadedFile.createNewFile();
}
Community
  • 1
  • 1
Anurag Anand
  • 500
  • 1
  • 7
  • 13
  • @AkhilNair change the directory.. make a temp folder in the server and try using that folder. If there is `right issue` on `users` folder , then ` uploadedFile.createNewFile();` will not create any file. Try using different folder. – Anurag Anand Jan 06 '15 at 03:22