@RequestMapping(method = RequestMethod.POST)
  public String onSubmit(FileUpload fileUpload, BindingResult errors, HttpServletRequest request)
      throws Exception {

    if (validator != null) { // validator is null during testing
      validator.validate(fileUpload, errors);

      if (errors.hasErrors()) {
        return "uploadForm";
      }
    }

    // validate a file was entered
    if (fileUpload.getFile().length == 0) {
      Object[] args = new Object[] {getText("uploadForm.file", request.getLocale())};
      errors.rejectValue("file", "errors.required", args, "File");

      return "uploadForm";
    }

    MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
    CommonsMultipartFile file = (CommonsMultipartFile) multipartRequest.getFile("file");

    // the directory to upload to
    String uploadDir =
        getServletContext().getRealPath("/resources") + "/" + request.getRemoteUser() + "/";

    // Create the directory if it doesn't exist
    File dirPath = new File(uploadDir);

    if (!dirPath.exists()) {
      dirPath.mkdirs();
    }

    // retrieve the file data
    InputStream stream = file.getInputStream();

    // write the file to the file specified
    OutputStream bos = new FileOutputStream(uploadDir + file.getOriginalFilename());
    int bytesRead;
    byte[] buffer = new byte[8192];

    while ((bytesRead = stream.read(buffer, 0, 8192)) != -1) {
      bos.write(buffer, 0, bytesRead);
    }

    bos.close();

    // close the stream
    stream.close();

    // place the data into the request for retrieval on next page
    request.setAttribute("friendlyName", fileUpload.getName());
    request.setAttribute("fileName", file.getOriginalFilename());
    request.setAttribute("contentType", file.getContentType());
    request.setAttribute("size", file.getSize() + " bytes");
    request.setAttribute(
        "location", dirPath.getAbsolutePath() + Constants.FILE_SEP + file.getOriginalFilename());

    String link = request.getContextPath() + "/resources" + "/" + request.getRemoteUser() + "/";
    request.setAttribute("link", link + file.getOriginalFilename());

    return getSuccessView();
  }
Пример #2
0
 @Override
 public File getFile() throws IOException {
   return fileUpload.getFile();
 }