2

i'm getting message "File not found". please help me. here id my code

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>

now, this is my 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>

}

same code is running perfectly without ajax.

  • Where do you get 'file not found' message (client or server)? – home Jan 14 '12 at 13:25
  • when i click upload button, after selecting the image file. Which means client side. –  Jan 14 '12 at 13:34
  • probably..i'm getting this error because, it's not sending the file to the servelet page. where, i've given the condition if (!isMultipart) { out.println("File Not Uploaded"); } –  Jan 14 '12 at 13:37
  • @home can you please tell me. what to do. or even tell me how to pass the file value to the servlet using ajax. I'll appreciate your help. please reply me as soon as possible. –  Jan 14 '12 at 14:10
  • Did you check [this](http://stackoverflow.com/questions/166221/how-can-i-upload-files-asynchronously-with-jquery)? – home Jan 14 '12 at 14:13
  • yes, i did. but, it's not helpful for me. can you just tell me. how to pass the file value to the servlet page using ajax. Because, i know, that's the problem, why i'm getting problem here. please help me.!! –  Jan 14 '12 at 14:31

2 Answers2

1

You can have a look for this ;)

Ajax File Upload to Java Servlet

Krack
  • 374
  • 1
  • 4
  • 7
1

use ajaxfileupload library to upload file using ajax.

below link may help you to upload file using ajax.

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