0

I made a JSP that is supposed to upload a file into a directory and it shows me an error when trying to connect: Here you can see my codes:

If anyone can help me i would appriciate it. package src;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import javax.servlet.RequestDispatcher;
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.FileItemFactory;
import org.apache.commons.fileupload.FileUploadBase;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FilenameUtils;


public class Controller extends HttpServlet {

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */


String saveFile="c:\\uploaddir\\";


protected void processRequest(HttpServletRequest request,         HttpServletResponse response)
            throws ServletException, IOException
{
    String actiune="afiseaza";
    PrintWriter out=response.getWriter();
    if (request.getParameter("actiune")!=null)
    {
        actiune = request.getParameter("actiune");
    }

    if (actiune.equals("afiseaza"))
    {
        doAfiseaza(request, response);
    }

    if (actiune.equals("sterge"))
    {
        doDeleteFile(request, response);
    }

    try{
            boolean ismultipart=ServletFileUpload.isMultipartContent(request);
             if(!ismultipart)
             {

             }
             else
             {
                 FileItemFactory factory= new DiskFileItemFactory();
                 ServletFileUpload upload= new ServletFileUpload(factory);
                 List items=null;

                 try{
                     items=upload.parseRequest(request);

                 }catch(Exception e)
                 {

                 }

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

                    if(item.isFormField())
                    {

                    }
                    else
                    {
                        String itemname=item.getName();
                        if((itemname==null)||itemname.equals(""))
                        {
                            continue;
                        }
                        String filename=FilenameUtils.getName(itemname);
                        File f=checkExist(filename);
                        item.write(f);

                    }


                 }

             }

        }catch(Exception e)
        {

        }
        finally{
        out.close();




            }
}
private void doDeleteFile(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException
{
    String fName=URLDecoder.decode(request.getParameter("fis"));

    File f = new File("c:\\uploaddir\\"+fName);
    f.delete();

    doAfiseaza(request, response);
}

private void doAfiseaza(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException
{
    String dir = "c:\\uploaddir";
    int er = 0;
    File[] lista = null;

    try
    {
        File f = new File(dir);
        lista = f.listFiles();
    }
    catch(Exception ex)
    {
        er=-1;
    }

    request.setAttribute("eroare", new Integer(er));
    request.setAttribute("lista", lista);

    RequestDispatcher rd = request.getRequestDispatcher("WEB-INF/lista.jsp");
    rd.forward(request, response);
}

// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
 * Handles the HTTP <code>GET</code> method.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    processRequest(request, response);
}

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    processRequest(request, response);
}

/**
 * Returns a short description of the servlet.
 *
 * @return a String containing servlet description
 */
@Override
public String getServletInfo() {
    return "Prima aplicatie";
}// </editor-fold>

private File checkExist(String fileName) {

    File f=new File(saveFile+"/"+fileName);

    if(f.exists())
    {
       StringBuffer sb=new StringBuffer(fileName);
       sb.insert(sb.lastIndexOf("."), "-"+new Date().getTime());
       f=new File(saveFile+"/"+sb.toString());

    }
    return f;
}

}

so now i have no errors but it doesnt upload my folder so i dont know what to do.

nokse
  • 93
  • 7
  • Please, just paste your code in the question so it would be much easier to read. I've just took a look at the code and the error message: `reached end of file while parsing` and I guess that you've missed closing bracket `}` somewhere in your code. – Adam May 16 '16 at 18:33
  • I placed the } where it was missing but it shows another error when i try to submit the file . I edited the question , please look above. – nokse May 16 '16 at 18:58
  • It would be nice if you could help me please @Adam. – nokse May 16 '16 at 19:13
  • I'm not an expert in 'jsp'. Now, when you've posted your code I'm sure that someone here will help you. I can only say that now you have a `NullPointerException` that means you try to do something on an object that is `null`. Find and check your GlassFish Server Open Source Edition 4.1.1 logs for more details, hopefully containing the line number where this error occurs. Good luck! – Adam May 16 '16 at 19:29
  • Thank you sir for your help so far:) i hope someone will help me with this issue – nokse May 16 '16 at 19:31
  • http://stackoverflow.com/questions/37015292/how-to-get-uploaded-file-within-jsp-scriptlet – rickz May 16 '16 at 20:06
  • getting this error @rickz: java.nio.file.NoSuchFileException: null\atac.txt – nokse May 16 '16 at 20:24
  • Parsing a multi-part request is not easy. Why not let the container do it? Are you using Tomcat 8? – rickz May 16 '16 at 20:26
  • As i was waiting for someone to reply i actually tryed to use the commons file uploader so if you look above i will update the code. – nokse May 16 '16 at 20:31
  • @rickz it does not upload the files into the directory – nokse May 16 '16 at 20:39
  • Did you follow BalusC instructions at http://stackoverflow.com/questions/2422468/how-to-upload-files-to-server-using-jsp-servlet?rq=1 – rickz May 16 '16 at 21:00
  • No @rickz...i used a tutorial from youtube...im new in java dynamic programing and i need a video so i can follow some steps and understand. – nokse May 16 '16 at 21:26
  • I don't why your code doesn't work. You could add debugging lines and print some messages out to your console. Also, your catch blocks just swallow exceptions. So, if any were being thrown you wouldn't know about them. You could print stacktraces. – rickz May 17 '16 at 04:37

1 Answers1

0

Since your original question was about JSP, here is some demonstration code.

<%@ page import="java.util.*,
             java.io.*,
             org.apache.commons.fileupload.*,
             org.apache.commons.fileupload.servlet.*,
             org.apache.commons.fileupload.disk.*,
             org.apache.commons.fileupload.util.*"%>
<%
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    out.print("Request content length is " + request.getContentLength() + "<br/>"); 
    if(isMultipart){
        ServletFileUpload upload = new ServletFileUpload();
        FileItemIterator iter = upload.getItemIterator(request);
        FileItemStream item = null;
        String name = "";
        InputStream stream = null;
        while (iter.hasNext()){
            item = iter.next();
            name = item.getFieldName();
            stream = item.openStream();
            if(item.isFormField()){out.println("Form field " + name + " with value " 
                                           + Streams.asString(stream) + "<br/>");}
                else {
                    name = item.getName();
                    if(name != null && !"".equals(name)){
                        String fileName = new File(item.getName()).getName();
                        out.println("Client file " + item.getName() + " <br/>with file name "
                                                    + fileName + " uploaded.<br/>");

                        File file = new File("C:/uploaddir/" + fileName);
                        FileOutputStream fos = new FileOutputStream(file);
                        long fileSize = Streams.copy(stream, fos, true);
                        out.print(fileName 
                            + " was uploaded to the fileUploads folder. Size was " +
                                   fileSize + "<br/>");
                      }
                   }
        }
    } else out.print("Wrong request type!");
%> 

call that JSP with

<html><body>
         <form enctype="multipart/form-data" action="fileUpload3.jsp" method="post">
                <input type='file' name='file1'/><br/>
                <input type='file' name='file2'/><br/>
                <input type='file' name='file3'/><br/>
                Type message:<input type="text" name="message" /><br/>
                <input Type='submit' value='Submit'/>
         </form>
 </body></html>   

Put both files in your web app's root folder.

rickz
  • 4,324
  • 2
  • 19
  • 30