0

I have a form on my jsp page. In this form i choose a file (zip archive) and after click submmit call servlet to upload this file. For file upload im use Apache Commons FileUlpoad library. After upload im unzip archive. Them i do redict to this jsp.

jsp code:

<form action="Upload_Servlet" method="post" enctype="multipart/form-data">
   <div id="up">
       <input id="fileUpload1" type="file" name="filename1"value="Browse..."/>
   </div>
   <div>
        <input id="btnSubmit" type="submit" value="Загрузить">
        <input type="button" id="del" onclick="deleting()" value="Удалить">
   </div>
</form>

servlet code:

public class uploadfile extends HttpServlet
{

public void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, java.io.IOException {
    System.out.println(response.getCharacterEncoding());
    response.setCharacterEncoding("UTF-8");
    System.out.println(response.getCharacterEncoding());
    response.setContentType("text/html");
    PrintWriter writer = response.getWriter();
    writer.println("wtpwebapps<br/>");
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    if (!isMultipart) {
        writer.println("<HTML>");
            writer.println("<HEAD <TITLE> Upload4 </TITLE> </HEAD>");
            writer.println("<BODY>");
            writer.println("<FORM action = \"Upload_Servlet\" method = \"post\" enctype = \"multipart/form-data\">");
            writer.println("<INPUT type = file name = ufile>");
            writer.println("<INPUT type = submit value = \"Attach\">");
            writer.println("<h1>its not multipart</h1>");
            writer.println("</FORM>");
            writer.println("</BODY>");
            writer.println("</HTML>");
            return;
        }          
  FileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
    List<FileItem> list=null;
    String mifpath= "1";
    String path = " ";
    String mif = " ";
    String from = "\\\\";
    String to ="/";
    String error="";
     try{
      list = upload.parseRequest(request);
      Iterator<FileItem> it = list.iterator();
      response.setContentType("text/html");
      while ( it.hasNext() ) 
      {

        FileItem item = (FileItem) it.next();
        File disk = new File("C:/uploaded_files/"+item.getName());

            path = disk.toString();

            String code = new String(path.substring(path.lastIndexOf("."), path.length()).getBytes("ISO-8859-1"),"utf-8");
            if (code.equalsIgnoreCase(".zip"))
            {
                mifpath=path;
                mif = mifpath.replaceAll(from, to);
                item.write(disk);
                error=unzip.unpack(mif, "C:/uploaded_files");
            }
            else
            {
                error = "Выбранный файл не является архивом zip";

            }
      }
    }
     catch ( Exception e ) {
      log( "Upload Error" , e);
    }
     request.setAttribute("error", error);
     request.getRequestDispatcher("/Home.jsp").forward(request, response);

    // String redictedURL="http://localhost:8080/redicted_test/Home.jsp";
    // response.sendRedirect(redictedURL);
    writer.close();
    }
}

Now i want to do this on the portal. Its mean that i dont want to reload my jsp after I upload a file. So i have to use Jquery. And i have some questions:

  1. How to submit form to use jquery in my case?
  2. My servlet code will be work in portlet?
  3. How to send parametrs to jps from portlet?
4

1 回答 1

0

Using Jquery it can be done easily:

  1. Set a click event on the submit button (or on the form submit).
  2. Post data to servlet:

    $.ajax({
            url : base_url + 'Upload_Servlet',
            type : "post",
            data:$('form').serialize(),             
            cache : false,
            success : function(data) {
                //do some stuff
    
        },
        error : function(xhr, status, err) {
            //do error stuff
        },
        timeout : 3000
        });
        //End ajax call
    
  3. After the servlet is done, just use the response writer to write an aswer back (If it contains a lot of data, I'd recommend sending a response in the form of json, see here) and then the success callback is called and you can do whatever you like with this data.

IMPORTANT: Since you are submitting a form, you need to use e.preventDefault() so the form will not be actually submitted but rather be handeled by your ajax.

于 2012-06-27T11:55:10.047 回答