java fileUpload multiparts返回null

时间:2017-07-20 21:47:18

标签: jsp apache-commons-fileupload

我的代码无法获取文件名。基本上它写入结果页面上传成功但它没有显示文件名并且没有上传到ftp服务器。它在数据库中保存null。请问有人帮我吗?以下是所有代码:

UserDao.java:

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

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

import java.io.IOException;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
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 javax.servlet.http.HttpSession;

@WebServlet(name = "UserDao", urlPatterns = {"/UserDao"})
@MultipartConfig()

public class UserDao extends HttpServlet {

private final String UPLOAD_DIRECTORY = "/upload";

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    try (PrintWriter out = response.getWriter()) {
        HttpSession session = request.getSession(true);
String x = "";
            if (ServletFileUpload.isMultipartContent(request)) {
                try {
//                x += request;
                    List<FileItem> multiparts = new ServletFileUpload(
                            new DiskFileItemFactory()).parseRequest(request);
                    //File uploaded successfully

                    for (FileItem item : multiparts) {
                        String fileName = item.getName();
                        File file = new File(UPLOAD_DIRECTORY + File.separator + fileName);
                        item.write(file);
                        x += fileName + " @@ ";
                    }
                    request.setAttribute("message", "File Uploaded Successfully: " + UPLOAD_DIRECTORY + File.separator + x);
                } catch (Exception ex) {
                    request.setAttribute("message", "File Upload Failed due to " + ex);
                }
            } else {
                request.setAttribute("message",
                        "Sorry this Servlet only handles file upload request");
            }
        UsersPojo users = new UsersPojo();
            users.setId(Integer.parseInt(request.getParameter("idx")));
            users.setEmail(request.getParameter("email"));
            users.setFirstname(request.getParameter("first_name"));
            users.setLastname(request.getParameter("last_name"));
            users.setPhone("");
            users.setCity(request.getParameter("city"));
            users.setCountry(request.getParameter("country"));
            users.setJob_title(request.getParameter("job_title"));
            users.setCompany(request.getParameter("company"));
            users.setFollow(request.getParameter("follow"));
            users.setPicture(request.getParameter("picture"));
            users.setLogo(request.getParameter("logo"));
            UserDB.updateUser(users);
   request.getRequestDispatcher("/results.jsp").forward(request, response);

welcome.jsp:

<form method="post" action="UserDao" enctype="multipart/form-data">
                                        <div class="col-sm-7" >
                                            <input type="hidden" id="idx" name="idx" value="<%=id%>">
                                            <input type="hidden" id="email" name="email" value="<%=up.getEmail()%>">
                                            <input type="hidden" id="follow" name="follow" value="<%=up.getFollow()%>">
                                            <div class=" col-sm-12">
                                                <div class="form-group margin15">
                                                    <label for="first_name">First name<strong style="color: #f00">*</strong></label>
                                                    <input type="text" name="first_name" id="first_name" value="<%=up.getFirstname()%>" class="form-control" required>
                                                </div>
                                            </div>
                                            <div class=" col-sm-12">
                                                <div class="form-group margin15">
                                                    <label for="last_name">Last name<strong style="color: #f00">*</strong></label>
                                                    <input type="text" name="last_name" id="last_name" value="<%=up.getLastname()%>" class="form-control" required>
                                                    <p style="font-size: small;">*You wish to hide your last name:  write only the first letter</p>
                                                </div>
                                            </div>
                                            <div class=" col-sm-12">
                                                <div class="form-group margin15">
                                                    <label for="city">City<strong style="color: #f00">*</strong></label>
                                                    <input type="text" name="city" id="city" value="<%=up.getCity()%>" class="form-control" required>
                                                </div>
                                            </div>
                                            <div class=" col-sm-12">
                                                <div class="form-group margin15">
                                                    <label for="country">Country<strong style="color: #f00">*</strong></label>
                                                    <input type="text" name="country" id="country" value="<%=up.getCountry()%>" class="form-control" required>
                                                </div>
                                            </div>
                                            <div class=" col-sm-12">
                                                <div class="form-group margin15 topmargin30">
                                                    <label for="job_title">Your job title<strong style="color: #f00">*</strong></label>
                                                    <input type="text" name="job_title" id="job_title" value="<%=up.getJob_title()%>" class="form-control" required>
                                                </div>
                                            </div>
                                            <div class=" col-sm-12">
                                                <div class="form-group margin15">
                                                    <label for="company">Your company<strong style="color: #f00">*</strong></label>
                                                    <input type="text" name="company" id="company" value="<%=up.getCompany()%>" class="form-control" required>
                                                </div>
                                            </div>
                                            <div class="col-sm-12" style="margin-top: 20px;color: #f00; font-size: 20px"><strong style="color: #f00; font-size: 23px">*</strong> Required</div>
                                        </div>
                                        <div class="col-sm-5" style="margin-top:10px">
                                            <div class="paddingprof widget">
                                                <div class="user-photo" style="padding: 0px; ">
                                                    <img src="assets/img/capture2.png" alt="User Photo" class="" style="border-radius: 0px">
                                                </div>
                                                <!-- /.user-photo -->
                                                <div class="background-white">
                                                    <h4 style="text-align: center">Upload your photo</h4>
                                                    <input type="file" name="picture" id="picture">
                                                </div>
                                            </div>
                                            <!-- /.widget -->
                                            <!--                                    <div class="paddingprof widget">
                                                                                   <div class="user-photo"  style="padding: 0px;">
                                                                                      <img src="assets/img/airbus.png" alt="User Photo" style="border-radius: 0px">
                                                                                   </div>
                                                                                   <div class="background-white">
                                                                                      <h4 style="text-align: center">Upload your logo</h4>
                                                                                      <input type="file" name="logo" id="logo" >
                                                                                   </div>
                                                                                </div>-->
                                            <!-- /.widget -->
                                        </div>

                                        <div class="col-sm-12" style="text-align: center">
                                            <button type="submit" name="btnEditComp" id="btnEditComp" class="btn1 btn btn-lg btn-primary" style="font-size: 23px;padding-right: 35px;padding-left: 35px;" >
                                                Save
                                            </button>
                                        </div>
                                    </form>

results.jsp:

<h3>${requestScope["message"]}</h3>

2 个答案:

答案 0 :(得分:0)

您至少需要添加空检查:

if (fileName != null) {
    File file = new File(UPLOAD_DIRECTORY + File.separator + fileName);
    item.write(file);
    x += fileName + " @@ ";
}

变量multiparts包含其他字段的DiskFileItem个实例,例如idxemailfirst_name,...而且它们不是有一个文件名。

答案 1 :(得分:0)

以下行返回多部分表单的所有项目:

List<FileItem> multiparts = new ServletFileUpload(
                            new DiskFileItemFactory()).parseRequest(request);

因此,在处理上传的文件时,您需要排除其余的表单项:

                for (FileItem item : multiparts) {
                    if (!item.isFormField()) {
                       String fileName = item.getName();
                       File file = new File(UPLOAD_DIRECTORY + File.separator + fileName);
                       item.write(file);
                       x += fileName + " @@ ";
                    }
                 }