Esempio n. 1
0
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
      // Just echo the parameters and values back as plain text
      resp.setContentType("text/plain");
      resp.setCharacterEncoding("UTF-8");

      PrintWriter out = resp.getWriter();

      out.println(
          "parts=" + (null == req.getParts() ? "null" : Integer.valueOf(req.getParts().size())));
    }
  @Override
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    HttpSession session = request.getSession();
    String roomname = (String) session.getAttribute("roomname");
    Logger logger = Logger.getLogger(FileUploadServlet.class);
    String caminho = getServletContext().getRealPath("\\image\\");

    String BASE_DIR = caminho + roomname;

    response.setContentType("text/html;charset=UTF-8");

    FileService service = new FileService();

    Path destination = service.createFolder(BASE_DIR);

    for (Part part : request.getParts()) {
      if (Files.exists(destination)) {
        service.saveFile(destination, part);
      }
    }

    request.setAttribute("message", "Upload has been done successfully!");
    request.setAttribute("fileEntities", service.findAll());

    getServletContext().getRequestDispatcher("/file-list.jsp").forward(request, response);
  }
  /** prepara los archivos enviados desde el clienta para su interpretacion (maximo de cinco) */
  public boolean ejecutar(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    // TODO Auto-generated method stub
    // leer base de datos
    Collection<Part> partes = request.getParts();
    @SuppressWarnings("unused")
    ProcesaDAOUsuario db = new ProcesaDAOUsuario(this.ds, this.sql);
    @SuppressWarnings({"unchecked", "rawtypes"})
    HashMap<Archivo, String> listaarchivosubido = new HashMap();
    this.Modelo = new ModeloAjax();
    for (Part trozo : partes) {
      if (trozo != null) {
        Archivo archivo = new Archivo(getNombreArchivo(trozo), trozo.getInputStream());
        if (archivo.isArchivo()) {
          listaarchivosubido.put(archivo, "correcto");

        } else {
          listaarchivosubido.put(
              archivo, "formato de archivo incorrecto(boe 105 del 3/5/2005 pag 15128)");
        }
      }
    }

    this.Modelo.setRespuesta(preparerarModelo(listaarchivosubido));
    this.Modelo.setContentType("text/html; charset=UTF-8");
    return true;
  }
Esempio n. 4
0
  public void doPost(HttpServletRequest req, HttpServletResponse resp)
      throws IOException, ServletException {
    String filename = "";
    Logger logger = Logger.getLogger(this.getClass().getCanonicalName());
    req.setCharacterEncoding("UTF-8");
    resp.setContentType("text/html;charset=UTF-8");
    String path = "/home/roman/uploads";

    FileWriter fw = new FileWriter("my.properties");
    Properties props = new Properties();
    props.setProperty("user.name", "Роман");
    props.store(fw, "Some commets about this version");
    fw.close();

    // getServletContext().getRealPath("") + File.separator + "uploads";
    PrintWriter out = resp.getWriter();
    try {
      Part p = req.getPart("content");
      if (p != null) {
        // req.getPart("content").write(path+filename);
        filename = getFileName(p);
        for (Part part : req.getParts()) {
          logger.info("Saving parts: " + filename);
          part.write(path + File.separator + filename);
        }
        logger.info("uploaded file: " + filename);
        out.write("<h3>" + path + File.separator + filename + "</h3>");
      }
    } catch (IllegalStateException e) {
      out.write("<h3>" + e.getMessage() + ", upload limit 5Mb</h3>");
      // resp.sendError(HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE);
    }
  }
 /** @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */
 protected void doPost(HttpServletRequest request, HttpServletResponse response)
     throws ServletException, IOException {
   // TODO Auto-generated method stub
   String appPath = request.getServletContext().getRealPath("");
   String filePath = "";
   for (Part part : request.getParts()) {
     String fileName = extractFileName(part);
     filePath = appPath + File.separator + fileName;
     part.write(filePath);
     System.out.println("Wrote file to " + appPath + File.separator + fileName);
   }
   CSVReader reader = new CSVReader(new FileReader(filePath));
   String[] nextLine;
   ArrayList<DataBean> data = new ArrayList<DataBean>();
   while ((nextLine = reader.readNext()) != null) {
     // nextLine[] is an array of values from the line
     System.out.println(nextLine[0] + nextLine[1]);
     DataBean bean = new DataBean();
     bean.setUsername(nextLine[0]);
     bean.setPassword(nextLine[1]);
     data.add(bean);
   }
   // Remove Username,password header
   data.remove(0);
   request.setAttribute("data", data);
   request.getRequestDispatcher("output.jsp").forward(request, response);
 }
Esempio n. 6
0
  protected Properties getParams(HttpServletRequest req)
      throws UnsupportedEncodingException, IOException, ServletException {
    String contentType = req.getContentType();
    Collection<Part> parts = null;
    try {
      parts = req.getParts();
    } catch (Exception e) {
      log.debug("Error parsing request parts " + e.getMessage());
    }

    if (parts != null && !parts.isEmpty()) {
      Properties props = new Properties();
      for (Part p : parts) {
        String realContent = getContentFromPart(p);
        props.put(p.getName(), realContent);
      }
      return props;
    } else {
      Properties props = null;
      if (contentType.indexOf("application/x-www-form-urlencoded") >= 0) {
        String result = URLDecoder.decode(getFullContent(req), encoding);
        props = ParamGetter.getProps(result);

      } else if (contentType.indexOf("multipart/form-data") >= 0) {
        MultipartParser parser = new MultipartParser(req, MAXPARAMSIZE);
        props = ParamGetter.getProps(parser);
      } else {
        log.error("Cannot parse contentType of " + contentType);
        throw new IOException("Bad content type of " + contentType);
      }
      return props;
    }
  }
Esempio n. 7
0
 public Collection<Part> parts() {
   try {
     return raw.getParts();
   } catch (IOException ex) {
     ex.printStackTrace();
     return null;
   } catch (ServletException ex) {
     ex.printStackTrace();
     return null;
   }
 }
  // override 'POST' handler. Appliction will use 'POST' to send 'multipart/form-data'
  @Override
  protected void doPost(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {

    /*
     * check content type. Require 'multipart/form-data' header in most case contains more than value, some parameters are
     * present so make a check with String.contains(String). send 406, with error message if it does not contain proper type
     */
    final String reqContentType = req.getContentType();

    if (!reqContentType.contains("multipart/form-data")) {
      logger.severe("Received request which is not mulipart: " + reqContentType);
      resp.sendError(406, "Received request which is not mulipart: " + reqContentType);
      return;
    }

    /*
     * In servlet 3.0, Parts carry form data. Get Parts and perform some name & type checks. Parts contain all data sent in
     * form not only file, we need only file.
     */
    Collection<Part> fileParts = req.getParts();
    if (fileParts != null && fileParts.size() > 0) {
      for (Part p : fileParts) {
        String partContentType = p.getContentType();
        String partName = p.getName();
        if (partContentType != null
            && partContentType.equals("text/xml")
            && partName != null
            && partName.equals(INPUT_NAME)) {

          InputStream is = p.getInputStream();
          fileUploadBean.parseUpload(is);
          break;
        }
      }
    }
    /*
     * Fetch dispatcher for '/'. This will make 'rd' initialized to dispatcher handling for application root.
     */
    RequestDispatcher rd = getServletContext().getRequestDispatcher("/");

    if (rd != null) {
      /*
       * Forward the request to default servlet handling calls to application root. In our case FacesServlet
       */
      rd.forward(req, resp);
      return;
    } else {
      // this is bad thing, lets throw exception to make user aware of that?
      throw new IllegalStateException("Container is not well!");
    }
  }
Esempio n. 9
0
 private Object[] parsePost(HttpServletRequest req) throws BrijjException {
   List<Object> lf = new LinkedList<Object>();
   if (isMultipartContent(req)) {
     try {
       Collection<Part> p = req.getParts();
       /*for (int i = 0; i < p.size(); i++)
       lf.add(null);
       */
       for (Part z : p) {
         String n = z.getName();
         Object o = readObject(z);
         // lf.set(Integer.valueOf(z.getName().substring(1)), readObject(z));
         lf.add(o);
       }
       return lf.toArray();
     } catch (ServletException sx) {
       throw new BrijjException(sx);
     } catch (IOException ix) {
       throw new BrijjException(ix);
     }
   } else {
     BufferedReader in = null;
     try {
       String ce = req.getCharacterEncoding();
       InputStream is = req.getInputStream();
       InputStreamReader isr =
           ce != null ? new InputStreamReader(is, ce) : new InputStreamReader(is);
       in = new BufferedReader(isr);
       while (true) {
         String line = in.readLine();
         if (line == null) return lf.toArray();
         if (line.indexOf('&') == -1) lf.add(readObject(line));
         // If there are any &'s then this must be iframe post
         else {
           StringTokenizer st = new StringTokenizer(line, "&");
           while (st.hasMoreTokens()) lf.add(readObject(urlDecode(st.nextToken())));
         }
       }
     } catch (Exception ex) {
       throw new BrijjException("Failed to read input", ex);
     } finally {
       if (in != null)
         try {
           in.close();
         } catch (IOException ex) {
         }
     }
   }
 }
Esempio n. 10
0
  @Override
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    HttpSession session = request.getSession();
    String username = "";
    for (Part part : request.getParts()) {
      if (part.getName().equals("message")) {
        part.delete();
        break;
      }
      String type = part.getContentType();

      if (!type.startsWith("image/")) {
        request.setAttribute("invalidType", true);
        RequestDispatcher rd = request.getRequestDispatcher("upload.jsp");
        rd.forward(request, response);
      }
      String filename = part.getSubmittedFileName();

      InputStream is = request.getPart(part.getName()).getInputStream();
      int i = is.available();

      LoggedIn lg = (LoggedIn) session.getAttribute("LoggedIn");

      if (lg.getlogedin()) {
        username = lg.getUsername();
        if (i > 0) {
          byte[] b = new byte[i + 1];
          is.read(b);
          PicModel tm = new PicModel();
          tm.setCluster(cluster);
          String description = request.getParameter("message");
          if (session.getAttribute("Location").equals("profile")) {
            tm.insertPic(b, type, filename, username, description, true);
          } else {
            tm.insertPic(b, type, filename, username, description, false);
          }
          is.close();
        }
      }
    }
    if (session.getAttribute("Location").equals("profile")) {
      response.sendRedirect("UserProfile");
    } else {
      response.sendRedirect("/InstagrimXinyue/Images/" + username);
    }
  }
Esempio n. 11
0
  /** @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    // gets absolute path of the web application
    String appPath = request.getServletContext().getRealPath("");
    // constructs path of the directory to save uploaded file
    String savePath = appPath + File.separator + SAVE_DIR;

    String fileName = System.currentTimeMillis() + "";

    // creates the save directory if it does not exists
    File fileSaveDir = new File(savePath);
    if (!fileSaveDir.exists()) {
      fileSaveDir.mkdir();
    }

    for (Part part : request.getParts()) {
      part.write(savePath + File.separator + fileName);
    }

    response.getWriter().append("{\"code\": \"" + fileName + "\"}");
  }
  @Override
  public void decode(FacesContext context, UIComponent component) {

    rendererParamsNotNull(context, component);

    if (!shouldDecode(component)) {
      return;
    }

    String clientId = decodeBehaviors(context, component);

    if (clientId == null) {
      clientId = component.getClientId(context);
    }

    assert (clientId != null);
    ExternalContext externalContext = context.getExternalContext();
    Map<String, String> requestMap = externalContext.getRequestParameterMap();

    if (requestMap.containsKey(clientId)) {
      setSubmittedValue(component, requestMap.get(clientId));
    }

    HttpServletRequest request = (HttpServletRequest) externalContext.getRequest();
    try {
      Collection<Part> parts = request.getParts();
      List<Part> multiple = new ArrayList<>();
      for (Part cur : parts) {
        if (clientId.equals(cur.getName())) {
          component.setTransient(true);
          multiple.add(cur);
        }
      }
      this.setSubmittedValue(component, multiple);
    } catch (IOException | ServletException ioe) {
      throw new FacesException(ioe);
    }
  }
Esempio n. 13
0
 protected void doPost(HttpServletRequest request, HttpServletResponse response)
     throws ServletException, IOException {
   // TODO 上传一张照片,Servlet3.0支持文件上传
   Collection<Part> photoList = request.getParts();
 }
  protected void doPost(
      HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
      throws ServletException, IOException {

    // CORS ORIGIN RESPONSE HEADER
    httpServletResponse.setHeader(
        "Access-Control-Allow-Origin",
        config.getProperty(HBNGStatics.CORS_ACCESS_CONTROL_ALLOW_ORIGIN_IDENTIFIER));

    // work on headers
    String authorization = "";
    String contenttype = "";

    Enumeration<String> headerNames = httpServletRequest.getHeaderNames();
    while (headerNames.hasMoreElements()) {

      String headerNameKey = headerNames.nextElement();
      this.logger.debug(
          "headerNameKey = "
              + headerNameKey
              + " / headerNameValue = "
              + httpServletRequest.getHeader(headerNameKey));

      if (headerNameKey.equals("Authorization")) {
        authorization = httpServletRequest.getHeader(headerNameKey);
      }
      if (headerNameKey.equals("Content-Type")) {
        contenttype = httpServletRequest.getHeader(headerNameKey);
      }
    }

    this.logger.info("contenttype = " + contenttype);

    // work on parameters
    String id = "";

    if (httpServletRequest.getParameter("uuid") != null
        && !httpServletRequest.getParameter("uuid").equals("")) {

      id = httpServletRequest.getParameter("uuid");
    } else {

      id = UUID.randomUUID().toString();
    }
    this.logger.info("ID: " + id);

    // constructs path of the directory to save uploaded file
    String savePath = this.config.getProperty("multipart.path.uploadedFiles") + File.separator + id;

    // creates the save directory if it does not exists
    File fileSaveDir = new File(this.config.getProperty("multipart.path.base") + savePath);
    if (!fileSaveDir.exists()) {

      this.logger.info("Verzeichnis existiert nicht! Lege '" + savePath + "' an.");
      fileSaveDir.mkdir();
    } else {

      this.logger.info("Verzeichnis '" + savePath + "' existiert!");
    }

    // work on request parts
    try {

      String modsData = null;
      String modsDataContentType = null;
      String cslData = null;
      String cslDataContentType = null;
      HashMap<String, HashMap<String, String>> swordTasks =
          new HashMap<String, HashMap<String, String>>();

      boolean isTask = true;

      for (Part part : httpServletRequest.getParts()) {

        // new publications as file upload
        if (part.getName().startsWith("file-")) {

          String fileName = extractFileName(part);
          this.logger.info("partname: " + part.getName() + "; filename: " + fileName);

          part.write(savePath + File.separator + fileName);

          // TODO create new Ticket

          isTask = false;
        }
        // Uploads
        else if (part.getName().startsWith("resource-") && part.getName().endsWith("-file")) {

          String fileName = extractFileName(part);
          this.logger.info("partname: " + part.getName() + "; filename: " + fileName);

          part.write(savePath + File.separator + fileName);

          // add to SWORD-Task
          if (!swordTasks.containsKey(part.getName().split("-file")[0])) {

            HashMap<String, String> swordTask = new HashMap<String, String>();

            swordTask.put("file", fileName);

            swordTasks.put(part.getName().split("-file")[0], swordTask);
          } else {

            swordTasks.get(part.getName().split("-file")[0]).put("file", fileName);
          }
        } else if (part.getName().startsWith("resource-") && part.getName().endsWith("-type")) {

          String value =
              new BufferedReader(new InputStreamReader(part.getInputStream()))
                  .lines()
                  .collect(Collectors.joining(System.lineSeparator()));

          this.logger.info(part.getName() + ": " + value);

          // add to SWORD-Task
          if (!swordTasks.containsKey(part.getName().split("-type")[0])) {

            HashMap<String, String> swordTask = new HashMap<String, String>();

            swordTask.put("type", value);

            swordTasks.put(part.getName().split("-type")[0], swordTask);
          } else {

            swordTasks.get(part.getName().split("-type")[0]).put("type", value);
          }
        } else if (part.getName().startsWith("resource-") && part.getName().endsWith("-note")) {

          String value =
              new BufferedReader(new InputStreamReader(part.getInputStream()))
                  .lines()
                  .collect(Collectors.joining(System.lineSeparator()));

          this.logger.info(part.getName() + ": " + value);

          // add to SWORD-Task
          if (!swordTasks.containsKey(part.getName().split("-note")[0])) {

            HashMap<String, String> swordTask = new HashMap<String, String>();

            swordTask.put("note", value);

            swordTasks.put(part.getName().split("-note")[0], swordTask);
          } else {

            swordTasks.get(part.getName().split("-note")[0]).put("note", value);
          }
        } else if (part.getName().startsWith("dataset-mods")) {

          modsData =
              new BufferedReader(new InputStreamReader(part.getInputStream()))
                  .lines()
                  .collect(Collectors.joining(System.lineSeparator()));
          modsDataContentType = part.getContentType();

          this.logger.debug(part.getName() + ": " + modsData);
        } else if (part.getName().startsWith("dataset-csl")) {

          cslData =
              new BufferedReader(new InputStreamReader(part.getInputStream()))
                  .lines()
                  .collect(Collectors.joining(System.lineSeparator()));
          cslDataContentType = part.getContentType();

          this.logger.debug(part.getName() + ": " + cslData);
        } else {

          this.logger.info(
              part.getName()
                  + ": "
                  + new BufferedReader(new InputStreamReader(part.getInputStream()))
                      .lines()
                      .collect(Collectors.joining(System.lineSeparator())));
        }
      }

      String data = "";

      try {

        data =
            httpServletRequest
                .getReader()
                .lines()
                .collect(Collectors.joining(System.lineSeparator()));
        this.logger.info("RequestBody is not empty!");
        this.logger.info("data: " + data);

      } catch (Exception e) {

        this.logger.info("RequestBody is empty!");
      }

      // validate existence of modsData and its content type > SC_NO_CONTENT
      if (modsData == null || modsData.equals("")) {

        this.logger.error(HttpServletResponse.SC_NO_CONTENT + " - No Content");
        httpServletResponse.sendError(HttpServletResponse.SC_NO_CONTENT, "No Content");
      } else {

        // PROCESSING
        if (isTask) {

          // Migrate and POST to LDP
          String postableData = null;

          // bind interface Preprocessing
          if (Lookup.lookupAll(PreprocessingInterface.class).size() > 0) {

            PreprocessingInterface preprocessingInterface =
                Lookup.lookup(PreprocessingInterface.class);
            // init Authorization Service
            preprocessingInterface.init(this.config);

            postableData = preprocessingInterface.process(modsData);
          } else {

            // correct error handling
            this.logger.error(
                "["
                    + this.config.getProperty("service.name")
                    + "] "
                    + HttpServletResponse.SC_INTERNAL_SERVER_ERROR
                    + ": "
                    + "Authorization Interface not implemented!");
          }

          // POST MODS data to LDP
          boolean isModsDataPosted = false;

          if (postableData != null) {

            // POST as application/sparql-update to LinkedDataPlatform
            String sparql_url = this.config.getProperty("ldp.sparql-endpoint");

            // HTTP Request
            int timeout = Integer.parseInt(this.config.getProperty("ldp.timeout"));

            RequestConfig defaultRequestConfig =
                RequestConfig.custom()
                    .setSocketTimeout(timeout)
                    .setConnectTimeout(timeout)
                    .setConnectionRequestTimeout(timeout)
                    .build();

            try (CloseableHttpClient httpclient =
                HttpClients.custom().setDefaultRequestConfig(defaultRequestConfig).build()) {

              HttpPost httpPost = new HttpPost(sparql_url);
              httpPost.addHeader("Content-Type", "application/sparql-update");
              httpPost.addHeader("Authorization", this.config.getProperty("ldp.authorization"));
              httpPost.setEntity(new StringEntity(postableData));

              CloseableHttpResponse httpResponse = null;

              long start = System.nanoTime();
              try {

                httpResponse = httpclient.execute(httpPost);
              } catch (ConnectTimeoutException | SocketTimeoutException e) {

                this.logger.info(
                    "["
                        + this.getClass().getName()
                        + "] "
                        + e.getClass().getName()
                        + ": "
                        + e.getMessage());
                httpResponse = httpclient.execute(httpPost);
              }
              long elapsed = System.nanoTime() - start;
              this.logger.info(
                  "["
                      + this.getClass().getName()
                      + "] LDP request - "
                      + (elapsed / 1000.0 / 1000.0 / 1000.0)
                      + " s");

              try {

                int statusCode = httpResponse.getStatusLine().getStatusCode();
                HttpEntity httpEntity = httpResponse.getEntity();

                if (statusCode == 200 || statusCode == 201) {

                  isModsDataPosted = true;
                } else {
                  this.logger.error(
                      "POST to LDP failed! - "
                          + statusCode
                          + ": "
                          + httpResponse.getStatusLine().getReasonPhrase());
                }

                EntityUtils.consume(httpEntity);

              } finally {
                httpResponse.close();
              }
            }
          }

          if (isModsDataPosted) {

            // TODO work on CSL data

            // TODO work on SWORD-Tasks
            // Interface Repository with implementation for SWORD using
            // https://github.com/swordapp/JavaClient2.0
            if (swordTasks.size() > 0) {

              for (String taskid : swordTasks.keySet()) {

                System.out.println("TASK: '" + taskid + "'");
                System.out.println("type: " + swordTasks.get(taskid).get("type"));
                System.out.println(
                    "file: "
                        + this.config.getProperty("multipart.path.base")
                        + savePath
                        + File.separator
                        + swordTasks.get(taskid).get("file"));
                System.out.println("note: " + swordTasks.get(taskid).get("note"));

                // TODO Was passiert mit den MODS- und ggf. CSL-Daten, wenn das hier schiefgeht?
                // 1. Möglichkeit: Lösche MODS und CSL und geben 500 zurück
                // 2. Möglichkeit: Kopiere die Dateien in ein "manuell bearbeiten"-Verzeichnis und
                // sende 201
                // Mein Favorit: 2. Möglichkeit
              }
            }
          }

          // last but not least: delete 'uploadFiles'-subfolder
          deleteTree(new File(this.config.getProperty("multipart.path.base") + savePath));
        }
      }

      // response
      httpServletResponse.setStatus(HttpServletResponse.SC_CREATED);
      httpServletResponse.getWriter().println("");
    } catch (Exception e) {

      this.logger.error("something went wrong", e);
      httpServletResponse.sendError(
          HttpServletResponse.SC_SERVICE_UNAVAILABLE, "something went wrong");
    }
  }
  public void doUpload(HttpServletRequest request, HttpServletResponse response)
      throws IOException, ServletException {
    if (!common.checkPost(request, response)) return;
    User user = common.requireLoggedInUser(request, response);
    if (user == null) return;

    DbxClient dbxClient = requireDbxClient(request, response, user);
    if (dbxClient == null) return;

    try {
      request.getParts(); // Just call getParts() to trigger the too-large exception.
    } catch (IllegalStateException ex) {
      response.sendError(400, "Request too large");
      return;
    }

    String targetFolder = slurpUtf8Part(request, response, "targetFolder", 1024);
    if (targetFolder == null) return;

    Part filePart = request.getPart("file");
    if (filePart == null) {
      response.sendError(400, "Field \"file\" is missing.");
      return;
    }
    String fileName = filePart.getName();
    if (fileName == null) {
      response.sendError(400, "Field \"file\" has no name.");
      return;
    }

    // Upload file to Dropbox
    String fullTargetPath = targetFolder + "/" + fileName;
    DbxEntry.File metadata;
    try {
      metadata =
          dbxClient.uploadFile(
              fullTargetPath, DbxWriteMode.add(), filePart.getSize(), filePart.getInputStream());
    } catch (DbxException ex) {
      common.handleDbxException(response, user, ex, "uploadFile(" + jq(fullTargetPath) + ", ...)");
      return;
    } catch (IOException ex) {
      response.sendError(400, "Error getting file data from you.");
      return;
    }

    // Display uploaded file metadata.
    response.setContentType("text/html");
    response.setCharacterEncoding("utf-8");
    PrintWriter out = new PrintWriter(new OutputStreamWriter(response.getOutputStream(), "UTF-8"));

    out.println("<html>");
    out.println("<head><title>File uploaded: " + escapeHtml4(metadata.path) + "</title></head>");
    out.println("<body>");
    out.println("<h2>File uploaded: " + escapeHtml4(metadata.path) + "</h2>");
    out.println("<pre>");
    out.print(escapeHtml4(metadata.toStringMultiline()));
    out.println("</pre>");
    out.println("</body>");
    out.println("</html>");

    out.flush();
  }
Esempio n. 16
0
 @Override
 public Collection<Part> getParts() throws IOException, IllegalStateException, ServletException {
   return request.getParts();
 }
 public static Object resolvePart(HttpServletRequest servletRequest) throws Exception {
   Collection<Part> parts = servletRequest.getParts();
   return parts.toArray(new Part[parts.size()]);
 }
  @Override
  public Object resolveArgument(
      MethodParameter parameter,
      ModelAndViewContainer mavContainer,
      NativeWebRequest request,
      WebDataBinderFactory binderFactory)
      throws Exception {

    HttpServletRequest servletRequest = request.getNativeRequest(HttpServletRequest.class);
    assertIsMultipartRequest(servletRequest);

    MultipartHttpServletRequest multipartRequest =
        WebUtils.getNativeRequest(servletRequest, MultipartHttpServletRequest.class);

    String partName = getPartName(parameter);
    Object arg;

    if (MultipartFile.class.equals(parameter.getParameterType())) {
      Assert.notNull(
          multipartRequest,
          "Expected MultipartHttpServletRequest: is a MultipartResolver configured?");
      arg = multipartRequest.getFile(partName);
    } else if (isMultipartFileCollection(parameter)) {
      Assert.notNull(
          multipartRequest,
          "Expected MultipartHttpServletRequest: is a MultipartResolver configured?");
      arg = multipartRequest.getFiles(partName);
    } else if (isMultipartFileArray(parameter)) {
      Assert.notNull(
          multipartRequest,
          "Expected MultipartHttpServletRequest: is a MultipartResolver configured?");
      List<MultipartFile> files = multipartRequest.getFiles(partName);
      arg = files.toArray(new MultipartFile[files.size()]);
    } else if ("javax.servlet.http.Part".equals(parameter.getParameterType().getName())) {
      assertIsMultipartRequest(servletRequest);
      arg = servletRequest.getPart(partName);
    } else if (isPartCollection(parameter)) {
      assertIsMultipartRequest(servletRequest);
      arg = new ArrayList<Object>(servletRequest.getParts());
    } else if (isPartArray(parameter)) {
      assertIsMultipartRequest(servletRequest);
      arg = RequestPartResolver.resolvePart(servletRequest);
    } else {
      try {
        HttpInputMessage inputMessage =
            new RequestPartServletServerHttpRequest(servletRequest, partName);
        arg = readWithMessageConverters(inputMessage, parameter, parameter.getParameterType());
        WebDataBinder binder = binderFactory.createBinder(request, arg, partName);
        if (arg != null) {
          validate(binder, parameter);
        }
        mavContainer.addAttribute(
            BindingResult.MODEL_KEY_PREFIX + partName, binder.getBindingResult());
      } catch (MissingServletRequestPartException ex) {
        // handled below
        arg = null;
      }
    }

    RequestPart annot = parameter.getParameterAnnotation(RequestPart.class);
    boolean isRequired = (annot == null || annot.required());

    if (arg == null && isRequired) {
      throw new MissingServletRequestPartException(partName);
    }

    return arg;
  }