0

JSP page:

<input type="file" name="scan_file" accept="application/pdf" id="scan_file" />

Pass file to java class:

$.ajax({
    type: "POST",   
    url: "bank_deposit1",        
    data: { 
       scan_file:$("#scan_file").val()
 },
success: function(response)
 {  
alert("done");
 },
 error: function(e)
{
alert("fail");
}});  

File cannot pass into java class.. Why?

sathya
  • 1,404
  • 2
  • 15
  • 26

1 Answers1

0

try this:

HTML form:

<form id="myForm" action="uploadFileData" method="post" enctype="multipart/form-data">
     Enter Your Name:
     <input type="text" name="yourname" id="yourname" /><br/>
     Select Your Photoes:
     <input type="file" name="file" id="file" />
     <input type="submit" value="save profile" />
</form>
<div id="response"></div>

and in js do like:

$('form#myForm').submit(function(event){    
    //disable the default form submission
      event.preventDefault();
    //grab all form data  
      var formData = new FormData($(this)[0]);  

    $.ajax({
        url: $(this).attr('action'),
        type: "POST",      
        cache: false,
        processData: false,
        contentType: false,
        data: formData,
        success: function (res) {
              $("#response").text(res); 
        },      
        error: function(jqXHR, textStatus, errorThrown) {
                alert(textStatus+' : '+ errorThrown);
             }

      });

});

Then in servlet save file like:

@WebServlet("/uploadFileData")
@MultipartConfig //in order to let it recognize and support multipart/form-data requests and thus get getPart() to work
public class UploadFileData extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private String UPLOAD_DIRECTORY;

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        UPLOAD_DIRECTORY = "E:\\";//request.getSession().getServletContext().getRealPath("/upload");

        // Set response content type
        response.setContentType("text/html");

        String yourname = request.getParameter("yourname");
        System.out.println(yourname);

        Part filePart = request.getPart("file");
        String fileName = getFileName(filePart);
        System.out.println("fileName:"+fileName);
        InputStream fileContent = filePart.getInputStream();

        System.out.println("upload dir: "+UPLOAD_DIRECTORY);
        File file = new File(UPLOAD_DIRECTORY+fileName);
        try{
            FileOutputStream fOutputStream = new FileOutputStream(file);
            try{
                byte[] bytes = new byte[8 * 1024];
                int bytesRead;
                while((bytesRead = fileContent.read(bytes)) != -1){
                    fOutputStream.write(bytes, 0, bytesRead);
                }
                System.out.println("file uploaded successfully..");
                response.getWriter().println("file uploaded successfully..");
            }finally{
                fOutputStream.close();
            }
        }finally{
            fileContent.close();
        }

    }

    /**
     * Utility method to extract file name from content-disposition.
     * @param filePart
     * @return file name
     */
    private String getFileName(Part filePart) {
        for(String cd: filePart.getHeader("content-disposition").split(";")){
            if(cd.trim().startsWith("filename")){
                String fileName = cd.substring(cd.indexOf('=')+1).trim().replace("\"", "");
                return fileName.substring(fileName.lastIndexOf('/') + 1).substring(fileName.lastIndexOf('\\') + 1); // MSIE fix.
            }
        }
        return null;
    }

}


for reference see this answer
Community
  • 1
  • 1
Abhishek Nayak
  • 3,732
  • 3
  • 33
  • 64
  • @sathya yes, any problem you faced with this solution?? – Abhishek Nayak Apr 01 '14 at 15:09
  • you should read some **tutorials**, and you should say as `Servlet` not `Action` if you say `Action` then people will understand as you talking about `Struts` and, here in my solution i have added comments, so please go through it. and if you not understand anything search or ask a question. – Abhishek Nayak Apr 01 '14 at 15:23
  • @sathya link added bottom have a look through it, you will get enough explanation there. – Abhishek Nayak Apr 01 '14 at 15:30
  • i didn't get you? Why getter and Setter not insert. means? please elaborate more. – Abhishek Nayak Apr 03 '14 at 11:48