Neal
Neal

Reputation: 463

uploading a file from jsp using servlets?

i am trying to upload an image from a jsp page using servlet. but how can i get the file in my servlet from the jsp file.

Upvotes: 1

Views: 575

Answers (2)

Rohhit
Rohhit

Reputation: 742

Here is My code which can help you.... :)

you can upload any type of image,pdf,txt using this code.

import org.apache.commons.fileupload.DiskFileUpload;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;

@SuppressWarnings("deprecation")
public class Upload extends HttpServlet  
{


/**
 * 
 */
private static final long serialVersionUID = 1L;
public void doPost(HttpServletRequest request,HttpServletResponse response) throws                IOException,ServletException
{


    System.out.println("inside upload.jsp");
    String filename="";

    //String login=session.getAttribute("studuser").toString();
    DiskFileUpload files=new DiskFileUpload();
    @SuppressWarnings("rawtypes")
    List list=null;
    try {
        list = files.parseRequest(request);
    } catch (FileUploadException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    @SuppressWarnings("rawtypes")
    Iterator itr=list.iterator();
    System.out.println("before while......");


    DBManager db=new DBManager();
    db.getConnect();
    @SuppressWarnings("unused")
    Connection con1=(Connection) db.con;


    while(itr.hasNext())
    {
        FileItem file=(FileItem)itr.next();
        filename=file.getName();
        System.out.println("**********"+filename);
        if(filename!=null)
        {
            int index=filename.lastIndexOf("/");

            filename=filename.substring(index+1);
            //System.out.println( application.getRealPath(""));
            File fNew=new File("F:/worksapce/Data-s/"+filename);
            try 
            {
                file.write(fNew);

            } 
            catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            System.out.println("after upload");




        }
    }
    response.sendRedirect("upload_success.jsp");

}

}

Upvotes: 1

Pierre
Pierre

Reputation: 35306

Look at the apache project http://commons.apache.org/fileupload/using.html or the cos library http://www.servlets.com/cos/

Upvotes: 2

Related Questions