文件上传写入路径Glassfish 4

时间:2014-03-28 17:27:13

标签: java file path glassfish-4

为了从HTML获取文件并使用Java和Glassfish 4将其复制到特定文件夹中。

这是我的jsp:

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Register</title>
    </head>
    <body>
        <h1>Register !</h1>
         <form method="post" enctype="multipart/form-data">
            <div>
                <label for="username">Username:</label>
                <input type="text" name="username" />
            </div>
             <div>
                <label for="username">E-mail:</label>
                <input type="text" name="mail" />
            </div>
            <div>
                <label for="password">Password:</label>
                <input type="password" name="password" />
            </div>
             <div>
               Select File to Upload: <input type="file" name="avatar"/>
            </div>
            <div>
                <input type="submit" value="Submit" />
            </div>
            <div>
                 <% 
                    String message = (String) request.getAttribute("erreur");
                    if(message != null)
                        out.println( message );
                %>
        </form>
    </body>
</html>

这是我的Servlet:

    @WebServlet(name = "RegisterServlet", urlPatterns = {"/Register"})
@MultipartConfig(fileSizeThreshold=1024*1024*10,    // 10 MB 
                 maxFileSize=1024*1024*50,          // 50 MB
                 maxRequestSize=1024*1024*100      // 100 MB
                 )
public class RegisterServlet extends HttpServlet {

    @EJB
    MyuserService MyuserService;

    private static final String SAVE_DIR = "uploads";

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getRequestDispatcher("/register.jsp").forward(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        String username = req.getParameter("username");
        String email = req.getParameter("mail");
        String password = req.getParameter("password");

        // Test des champs
        if(username == null || email == null || password == null){

            String erreur = "Merci de remplir les champs pour charger le formulaire!";
            req.setAttribute("erreur", erreur);
            doGet(req, resp);

        }
        else{

            Myuser user = new Myuser();
            user.setEmail(email);
            user.setPassword(password);
            user.setUserName(username);
            user.setCreationDate(new Timestamp(new java.util.Date().getTime()));
            user.setUserRole(Utils.__USERROLE_UTILISATEUR__);

            // gets absolute path of the web application
            String appPath = System.getProperty("user.dir");

            // constructs path of the directory to save uploaded file
            String savePath = appPath + File.separator + SAVE_DIR;

            // creates the save directory if it does not exists
            File fileSaveDir = new File(savePath);
            if (!fileSaveDir.exists()) {
                fileSaveDir.mkdir();
            }
            for (Part part : req.getParts()) {
                if (part.getName().equalsIgnoreCase("avatar")){
                    String fileName = extractFileName(part);
                    part.write(savePath + File.separator + fileName);
                }
            }

            // Ajout de l'utilisateur en BDD
            MyuserService.addMyuser(user);

            req.getSession().setAttribute("user", user.getUserName());
            resp.sendRedirect(getServletContext().getContextPath());

        }
    }

    /**
     * Extracts file name from HTTP header content-disposition
     */

    private String extractFileName(Part part) {
        String contentDisp = part.getHeader("content-disposition");
        String[] items = contentDisp.split(";");
        for (String s : items) {
            if (s.trim().startsWith("filename")) {
                return s.substring(s.indexOf("=") + 2, s.length()-1);
            }
        }
        return "";
    }

}

这是我的savePath变量返回:

/Applications/NetBeans/glassfish-4.0/glassfish/domains/domain1/config/uploads

错误:

java.io.FileNotFoundException: /Applications/NetBeans/glassfish-4.0/glassfish/domains/domain1/generated/jsp/Myapp/Applications/NetBeans/glassfish-4.0/glassfish/domains/domain1/config/uploads/Secu.txt (No such file or directory)
    at java.io.FileOutputStream.open(Native Method)
    at java.io.FileOutputStream.<init>(FileOutputStream.java:221)
    at java.io.FileOutputStream.<init>(FileOutputStream.java:171)
    at org.apache.catalina.fileupload.PartItem.write(PartItem.java:450)
    at org.apache.catalina.fileupload.PartItem.write(PartItem.java:505)
    at com.myapp.Servlet.RegisterServlet.doPost(RegisterServlet.java:77)

所以user.dir路径被解释为twiced ..

2 个答案:

答案 0 :(得分:0)

通过用以下方法替换我的MultipartConfig注释来解决:

@MultipartConfig(fileSizeThreshold=1024*1024*10,    // 10 MB 
                 maxFileSize=1024*1024*50,          // 50 MB
                 maxRequestSize=1024*1024*100,      // 100 MB
                 location="/")

答案 1 :(得分:0)

&#13;
&#13;
package client;


import javax.servlet.annotation.WebServlet;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletConfig;
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.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFac tory;
import org.apache.commons.fileupload.servlet.ServletFileU pload;

@
WebServlet("/UploadPicture")
public class UploadPicture extends HttpServlet {
  private static final long serialVersionUID = 1L;

  private static final String DESTINATION_DIR_PATH = "/files";
  private File destinationDir;

  public UploadPicture() {
    super();
  }

  public void init(ServletConfig config) throws ServletException {
    super.init(config);

    String realPath = getServletContext().getRealPath(DESTINATION_DIR_PA TH);
    destinationDir = new File(realPath);
    if (!destinationDir.isDirectory()) {
      throw new ServletException(DESTINATION_DIR_PATH + " is not a directory");
    }
  }

  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {}

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

    PrintWriter out = response.getWriter();
    response.setContentType("text/plain");


    DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();
    fileItemFactory.setSizeThreshold(1 * 1024 * 1024); //1 MB

    ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory);
    try {
      List < FileItem > items = uploadHandler.parseRequest(request);
      Iterator < FileItem > itr = items.iterator();
      while (itr.hasNext()) {
        FileItem item = (FileItem) itr.next();

        if (item.isFormField()) {
          out.println("File Name = " + item.getFieldName() + ", Value = " + item.getString());
        } else {

          out.println("Field Name = " + item.getFieldName() +
            ", File Name = " + item.getName() +
            ", Content type = " + item.getContentType() +
            ", File Size = " + item.getSize());

          File file = new File(destinationDir, item.getName());
          item.write(file);
        }
        out.close();
      }
    } catch (FileUploadException ex) {
      log("Error encountered while parsing the request", ex);
    } catch (Exception ex) {
      log("Error encountered while uploading file", ex);
    }
    request.getRequestDispatcher("/index.jsp");
  }

}
&#13;
<form action="UploadPicture" method="post" enctype="multipart/form-data">
  <input type="file" name="myFile">
  <input type="submit" value="Upload">
</form>
&#13;
&#13;
&#13;