使用ajax和servlet上传文件

时间:2012-01-14 12:24:17

标签: java ajax jsp servlets file-upload

我收到消息“未找到文件”。请帮我。 这里是我的代码

的index.jsp

<html>
<head>
<title>Ajax File Upload</title>
 <script type="text/javascript" src="jquery-1.4.2.min.js"></script>

        <script type="text/javascript">
            $(document).ready(function(){
                $("#login_frm").submit(function(){

                    //remove previous class and add new "myinfo" class
                    $("#msgbox").removeClass().addClass('myinfo').text('Validating Your Form ').fadeIn(1000);


                    this.timer = setTimeout(function () {
                        $.ajax({
                            url: 'uploads',
                            enctype: 'multipart/form-data',
                            data: 'filename='+ $('#file').val(),
                            type: 'post',                            
                            success: function(msg){
                                 $("#msgbox").removeClass().addClass('myinfo').text(msg).fadeIn(1000);
                            }

                        });
                    }, 200);
                    return false;
                });

            });

        </script>
 <link href="style.css" rel="stylesheet" type="text/css" />
 <link href="login_style.css" rel="stylesheet" type="text/css" />
</head>
<body>
    <form name="login_frm"  enctype="multipart/form-data" id="login_frm" action="" method="post">
           <div id="login_box">
                <div id="login_header">&nbsp;&nbsp;&nbsp;Citizen Login </div>
                <div id="form_val" style="background-color:black; height:80px;">
                    <div class="label">Upload Pic :</div>
                    <div class="control"><input type="file" name="file" id="file"/></div>
                    <div id="msgbox"></div>
                </div>
                  <div id="login_footer">
                          <label>
                        <input type="submit" name="upload" id="upload" value="Upload" class="send_button" />
                    </label>
                </div>
            </div>
        </form>
</body>
</html>

现在,这是我的servlet

uploads.java

package fileupload;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Iterator;
import java.io.File;
import java.util.Random;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.*;
import java.util.regex.*;


public class uploads extends HttpServlet {

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (!isMultipart) {
out.println("File Not Uploaded");
} else {
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List items = null;
try {
items = upload.parseRequest(request);
//out.println("items: "+items);
} catch (FileUploadException e) {
e.printStackTrace();
}
FileItem file = (FileItem)items.get(0);
//out.print(file);
Iterator itr = items.iterator();
int noFile=0;
while (itr.hasNext()) {

FileItem item = (FileItem) itr.next();
if (item.isFormField()){

String name = item.getFieldName();
String value = item.getString();
} else {
try {

String itemName = item.getName();
Random generator = new Random();
int r = Math.abs(generator.nextInt());
String reg = "[.*]";
String replacingtext = "";
Pattern pattern = Pattern.compile(reg);
Matcher matcher = pattern.matcher(itemName);
StringBuffer buffer = new StringBuffer();
while (matcher.find()) {
matcher.appendReplacement(buffer, replacingtext);
}
int IndexOf = itemName.indexOf(".");
String domainName = itemName.substring(IndexOf);
String finalimage = buffer.toString()+"_"+r+domainName;
File savedFile = new File("C:/tmp/"+"images\\"+finalimage);
item.write(savedFile);
} catch (Exception e) {
e.printStackTrace();
}
}
}
out.print(noFile+" File(s) Uploaded !!");
}
        } finally { 
            out.close();
        }
    } 

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    } 

    @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 "Short description";
    }// </editor-fold>

}

相同的代码在没有ajax的情况下运行良好。

2 个答案:

答案 0 :(得分:1)

使用ajaxfileupload库使用ajax上传文件。

链接下面的

可以帮助您使用ajax上传文件。

http://www.phpletter.com/Our-Projects/AjaxFileUpload/

答案 1 :(得分:1)

你可以看看这个;)

Ajax File Upload to Java Servlet