Java 如何将文件jsp页面传递给action类?

Java 如何将文件jsp页面传递给action类?,java,javascript,file,jsp,action,Java,Javascript,File,Jsp,Action,JSP页面: <input type="file" name="scan_file" accept="application/pdf" id="scan_file" /> 文件无法传递到java类。。为什么?试试这个: HTML格式: <form id="myForm" action="uploadFileData" method="post" enctype="multipart/form-data"> Enter Your Name: <i

JSP页面:

<input type="file" name="scan_file" accept="application/pdf" id="scan_file" />
文件无法传递到java类。。为什么?

试试这个:

HTML格式:

<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>
然后在servlet中保存文件,如下所示:

@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;
    }

}


作为参考

java类或servlet?运行时会发生什么?我得到一个错误:objectobject使您的问题更清楚。。通过添加错误,你得到了什么并突出了问题。@sathya是的,这个解决方案遇到的任何问题??你应该阅读一些教程,你应该说as
Servlet
而不是
Action
如果你说
Action
,那么人们就会理解你所说的
Struts
,并且,在我的解决方案中,我添加了注释,请仔细阅读。如果你不懂任何东西,搜索或问一个问题。@sathya-link在底部添加了一个链接,让你看一看,你会在那里得到足够的解释。我没听懂吗?为什么getter和Setter不插入。方法请详细说明。
$('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);
             }

      });

});
@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;
    }

}