无法使用jsp将文件上传到服务器

时间:2019-05-18 12:35:42

标签: java jsp

我正在尝试开发Java Web应用程序,其中需要将文件上传到服务器。我正在使用Xampp tomcat服务器,该服务器已集成到Eclipse应用程序中。选择要上传的文件后,我将在下一页收到文件上传失败状态消息。这是我的代码

fileUpload.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
        <title>FileUpload</title>
    </head>
    <body>
        <form  action="MsgProcessorServlet" method="post" enctype="multipart/form-data" id="uploadForm">
            <input type="file" name="file"/>
            <input type="hidden" name="formType" value="uploadXML"/>
        </form>
        <p>
            <button type="submit" form="uploadForm" id="Upload">Upload</button>
        </p>
    </body>
</html>

MsgProcessorServlet.java

package com.servlet;

import java.io.IOException;
import java.util.List;
import java.io.File;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 * Servlet implementation class MsgProcessorServlet
 */
@WebServlet("/MsgProcessorServlet")
@MultipartConfig
public class MsgProcessorServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public MsgProcessorServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        System.out.println(request.getParameter("formType"));
        if(request.getParameter("formType").equals("buildNew")) {
            request.setAttribute("message", "Files generated successfully");
            RequestDispatcher req = request.getRequestDispatcher("buildNewResult.jsp");
            req.forward(request, response);
        }
        else if(request.getParameter("formType").equals("uploadXML")) {
            request.setAttribute("message", "File Upload failed");
            if(ServletFileUpload.isMultipartContent(request)) {
                System.out.println("came here1");
                List<FileItem> multiparts = null;
                try {
                    DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
                    diskFileItemFactory.setSizeThreshold(5 * 1024 * 1024);

                    ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);
                    servletFileUpload.setSizeMax(5 * 1024 * 1024);

                    multiparts = servletFileUpload.parseRequest(request);
                } catch (FileUploadException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                System.out.print("multiParts size: ");
                System.out.println(multiparts.size());
                for(FileItem item : multiparts) {
                    System.out.println("came here2");
                    if(!item.isFormField()) {
                        String fileName = new File(item.getName()).getName();
                        System.out.println(fileName);
                        try {
                            request.setAttribute("message", "File Uploaded successfully");
                            item.write(new File("./" + fileName));
                        } catch (Exception e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                }
            }

            RequestDispatcher req = request.getRequestDispatcher("fileUploadResult.jsp");
            req.forward(request, response);
        }
    }

}

调用 ServletFileUpload parseRequest 方法时,不会填充 FileItem 类型的 multipleParts 列表。

1 个答案:

答案 0 :(得分:0)

尝试一下。工作代码。

  

Fileupload.java

import java.io.File;
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 * Servlet to handle File upload request from Client
 * @author Javin Paul
 */
public class Fileupload extends HttpServlet {
    private final String UPLOAD_DIRECTORY = "C:/uploads";

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        //process only if its multipart content
        if(ServletFileUpload.isMultipartContent(request)){
            try {
                List<FileItem> multiparts = new ServletFileUpload(
                                         new DiskFileItemFactory()).parseRequest(request);

                for(FileItem item : multiparts){
                    if(!item.isFormField()){
                        String name = new File(item.getName()).getName();
                        item.write( new File(UPLOAD_DIRECTORY + File.separator + name));
                    }
                }

               //File uploaded successfully
               request.setAttribute("message", "File Uploaded Successfully");
            } catch (Exception ex) {
               request.setAttribute("message", "File Upload Failed due to " + ex);
            }          

        }else{
            request.setAttribute("message",
                                 "Sorry this Servlet only handles file upload request");
        }

        request.getRequestDispatcher(/* redirect according to your need. */).forward(request, response); 

    }

}
  

Index.jsp

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>File Upload</title>
    </head>

    <body> 
        <div>
            <h3> Choose File to Upload in Server </h3>
            <form action="Fileupload" method="post" enctype="multipart/form-data">
                <input type="file" name="file" />
                <input type="submit" value="upload" />
            </form>          
        </div>

    </body>
</html>