Example usage for org.springframework.web.multipart.commons CommonsMultipartFile getOriginalFilename

List of usage examples for org.springframework.web.multipart.commons CommonsMultipartFile getOriginalFilename

Introduction

In this page you can find the example usage for org.springframework.web.multipart.commons CommonsMultipartFile getOriginalFilename.

Prototype

@Override
    public String getOriginalFilename() 

Source Link

Usage

From source file:com.amediamanager.dao.DynamoDbUserDaoImpl.java

/**
 * Upload the profile pic to S3 and return it's URL
 * @param profilePic/*from w w w  . ja  v  a  2s.  co  m*/
 * @return The fully-qualified URL of the photo in S3
 * @throws IOException
 */
public String uploadFileToS3(CommonsMultipartFile profilePic) throws IOException {

    // Profile pic prefix
    String prefix = config.getProperty(ConfigProps.S3_PROFILE_PIC_PREFIX);

    // Date string
    String dateString = new SimpleDateFormat("ddMMyyyy").format(new java.util.Date());
    String s3Key = prefix + "/" + dateString + "/" + UUID.randomUUID().toString() + "_"
            + profilePic.getOriginalFilename();

    // Get bucket
    String s3bucket = config.getProperty(ConfigProps.S3_UPLOAD_BUCKET);

    // Create a ObjectMetadata instance to set the ACL, content type and length
    ObjectMetadata metadata = new ObjectMetadata();
    metadata.setContentType(profilePic.getContentType());
    metadata.setContentLength(profilePic.getSize());

    // Create a PutRequest to upload the image
    PutObjectRequest putObject = new PutObjectRequest(s3bucket, s3Key, profilePic.getInputStream(), metadata);

    // Put the image into S3
    s3Client.putObject(putObject);
    s3Client.setObjectAcl(s3bucket, s3Key, CannedAccessControlList.PublicRead);

    return "http://" + s3bucket + ".s3.amazonaws.com/" + s3Key;
}

From source file:com.bbm.common.cmm.web.EgovMultipartResolver.java

/**
 * multipart?  parsing? .// www. j  a  v  a 2s. c  om
 */
@SuppressWarnings("unchecked")
@Override
protected MultipartParsingResult parseFileItems(List fileItems, String encoding) {
    Map multipartFiles = new HashMap();
    Map multipartParameters = new HashMap();

    // Extract multipart files and multipart parameters.
    for (Iterator it = fileItems.iterator(); it.hasNext();) {
        FileItem fileItem = (FileItem) it.next();

        if (fileItem.isFormField()) {

            String value = null;
            if (encoding != null) {
                try {
                    value = fileItem.getString(encoding);
                } catch (UnsupportedEncodingException ex) {
                    if (logger.isWarnEnabled()) {
                        logger.warn("Could not decode multipart item '" + fileItem.getFieldName()
                                + "' with encoding '" + encoding + "': using platform default");
                    }
                    value = fileItem.getString();
                }
            } else {
                value = fileItem.getString();
            }
            String[] curParam = (String[]) multipartParameters.get(fileItem.getFieldName());
            if (curParam == null) {
                // simple form field
                multipartParameters.put(fileItem.getFieldName(), new String[] { value });
            } else {
                // array of simple form fields
                String[] newParam = StringUtils.addStringToArray(curParam, value);
                multipartParameters.put(fileItem.getFieldName(), newParam);
            }
        } else {

            if (fileItem.getSize() > 0) {
                // multipart file field
                CommonsMultipartFile file = new CommonsMultipartFile(fileItem);
                if (multipartFiles.put(fileItem.getName(), file) != null) { // CHANGED!!
                    throw new MultipartException("Multiple files for field name [" + file.getName()
                            + "] found - not supported by MultipartResolver");
                }
                if (logger.isDebugEnabled()) {
                    logger.debug("Found multipart file [" + file.getName() + "] of size " + file.getSize()
                            + " bytes with original filename [" + file.getOriginalFilename() + "], stored "
                            + file.getStorageDescription());
                }
            }

        }
    }

    return new MultipartParsingResult(multipartFiles, multipartParameters);
}

From source file:egovframework.oe1.cms.com.web.EgovOe1MultipartResolver.java

/**
 * multipart?  parsing? ./* w ww  .  j  av  a2  s  .c  o  m*/
 */
@SuppressWarnings("unchecked")
@Override
protected MultipartParsingResult parseFileItems(List fileItems, String encoding) {
    Map multipartFiles = new HashMap();
    Map multipartParameters = new HashMap();

    // Extract multipart files and multipart parameters.
    for (Iterator it = fileItems.iterator(); it.hasNext();) {
        FileItem fileItem = (FileItem) it.next();

        if (fileItem.isFormField()) {

            String value = null;
            if (encoding != null) {
                try {
                    value = fileItem.getString(encoding);
                } catch (UnsupportedEncodingException ex) {
                    if (logger.isWarnEnabled()) {
                        logger.warn("Could not decode multipart item '" + fileItem.getFieldName()
                                + "' with encoding '" + encoding + "': using platform default");
                    }
                    value = fileItem.getString();
                }
            } else {
                value = fileItem.getString();
            }
            String[] curParam = (String[]) multipartParameters.get(fileItem.getFieldName());
            if (curParam == null) {
                // simple form field
                multipartParameters.put(fileItem.getFieldName(), new String[] { value });
            } else {
                // array of simple form fields
                String[] newParam = StringUtils.addStringToArray(curParam, value);
                multipartParameters.put(fileItem.getFieldName(), newParam);
            }
        } else {

            if (fileItem.getSize() > 0) {
                // multipart file field
                CommonsMultipartFile file = new CommonsMultipartFile(fileItem);
                if (multipartFiles.put(fileItem.getName(), file) != null) { // CHANGED!!
                    throw new MultipartException("Multiple files for field name [" + file.getName()
                            + "] found - not supported by MultipartResolver");
                }
                if (logger.isDebugEnabled()) {
                    logger.debug("Found multipart file [" + file.getName() + "] of size " + file.getSize()
                            + " bytes with original filename [" + file.getOriginalFilename() + "], stored "
                            + file.getStorageDescription());
                }
            }

        }
    }

    return new MultipartParsingResult((MultiValueMap<String, MultipartFile>) multipartFiles,
            (Map<String, String[]>) multipartParameters);
}

From source file:com.crimelab.controller.UploadController.java

@RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
public ModelAndView showCompositeDetails(Model model,
        @RequestParam(value = "file") CommonsMultipartFile uploadedFile,
        @RequestParam(value = "description", required = false) String fileDescription,
        @RequestParam(value = "sococase", required = false) String soco_case) throws IOException {
    Calendar currentTimeDate = Calendar.getInstance();
    File filePath = new File(fileUploadService.getFileUploadPath() + "\\Files\\");
    ModelAndView mv = new ModelAndView("redirect:FileUpload");

    if (!filePath.exists()) {
        filePath.mkdir();/*from   w  ww  .j  a va2  s. co m*/
    }
    String status = "success";
    try {
        uploadedFile.transferTo(new File(filePath + "\\" + uploadedFile.getOriginalFilename()));
    } catch (IllegalStateException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        status = "failure";
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        status = "iofailure";
    }

    int file_type;

    String fileType = uploadedFile.getContentType();
    String getFile = uploadedFile.getOriginalFilename();
    String[] fileExtension = getFile.split("\\.", 2);

    if (fileExtension[1].contains("doc") || fileExtension[1].contains("pdf")
            || fileExtension[1].contains("xls")) {
        file_type = 0;
    } else {
        file_type = 1;
    }

    Files input = new Files();

    input.setFile_type(file_type);
    input.setOrig_file_name(uploadedFile.getOriginalFilename());
    input.setFile_name(uploadedFile.getOriginalFilename());
    input.setFile_extension(fileExtension[1]);
    input.setFile_path(filePath.toString() + "\\" + uploadedFile.getOriginalFilename());
    input.setDate(currentTimeDate.getTime());
    input.setDescription(fileDescription);
    input.setSoco_case(soco_case);
    input.setFolder_id(1); // Related field
    fileUploadService.uploadFile(input);
    //site settings for fileLocation, to edit
    mv.addObject("status", status);
    return mv;
}

From source file:com.digitalizat.control.TdocController.java

@RequestMapping(value = "guardarFichero", method = RequestMethod.POST)
public String guardarFichero(@RequestParam(value = "file", required = true) CommonsMultipartFile file,
        @RequestParam(value = "idFolder", required = true) Integer idFolder, HttpServletRequest request,
        Model m) throws FileNotFoundException, IOException, Exception {
    HttpSession sesion = request.getSession();
    User usuarioLogado;/*w  w w .  ja  v  a 2s.  c om*/
    if (sesion.getAttribute("user") == null && (!(Boolean) sesion.getAttribute("logged"))) {
        throw new Exception("Login requerido");
    } else {
        usuarioLogado = (User) sesion.getAttribute("user");
    }
    File localFile = new File(serverProperties.getRutaGestorDocumental() + file.getOriginalFilename());
    FileOutputStream os;
    os = new FileOutputStream(localFile);
    os.write(file.getBytes());

    Document doc = new Document();
    doc.setBasePath(serverProperties.getRutaGestorDocumental());
    doc.setPathdoc("/" + usuarioLogado.getBranch().getId() + "/");
    doc.setBranch(usuarioLogado.getBranch());
    doc.setFileName(file.getOriginalFilename());
    if (idFolder != null && !idFolder.equals(new Integer(0))) {
        doc.setParent(tdocManager.getDocument(idFolder));
    }
    doc.setFolder(Boolean.FALSE);
    tdocManager.addDocument(doc);
    return "index.html#/tdoc";
}

From source file:alpha.portal.webapp.controller.FileUploadController.java

/**
 * On submit./*from w w w  . j  a va2  s . co  m*/
 * 
 * @param fileUpload
 *            the file upload
 * @param errors
 *            the errors
 * @param request
 *            the request
 * @return the string
 * @throws Exception
 *             the exception
 */
@RequestMapping(method = RequestMethod.POST)
public String onSubmit(final FileUpload fileUpload, final BindingResult errors,
        final HttpServletRequest request) throws Exception {

    if (request.getParameter("cancel") != null)
        return this.getCancelView();

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

        if (errors.hasErrors())
            return "fileupload";
    }

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

        return "fileupload";
    }

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

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

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

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

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

    // write the file to the file specified
    final OutputStream bos = new FileOutputStream(uploadDir + file.getOriginalFilename());
    int bytesRead;
    final 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());

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

    return this.getSuccessView();
}

From source file:com.necl.core.service.HandlerFileUpload.java

public void handleFileUploadToPath2(CommonsMultipartFile fileUpload, String username) throws Exception {

    Calendar now = Calendar.getInstance();
    //        int year = now.get(Calendar.YEAR);

    String keyFind = "PATH";
    ConfigSystem configSystem = configSystemService.findByKey(keyFind);
    String saveDirectory = configSystem.getConfigText();

    //        File file = new File(saveDirectory + File.separator + convertNameAndTypeFile(fileUpload.getOriginalFilename(), numberTicket));
    //        System.out.println("file: "+file);
    //        file.delete();
    if (fileUpload != null && fileUpload.getSize() > 0) {
        File files = new File(saveDirectory + File.separator
                + convertNameAndTypeFile2(fileUpload.getOriginalFilename(), username));
        if (!files.exists()) {
            files.mkdirs();//from w  w  w  . j  a v  a  2 s . c  om
        }
        if (!username.equals("")) {
            fileUpload.transferTo(files);
        }

    }

    // returns to the view "Result"
}

From source file:com.necl.core.service.HandlerFileUpload.java

public void handleFileUploadToPath(CommonsMultipartFile fileUpload, String numberTicket) throws Exception {

    Calendar now = Calendar.getInstance();
    //        int year = now.get(Calendar.YEAR);
    String yearInString = "20" + numberTicket.substring(3, 5);

    String keyFind = "PATH";
    ConfigSystem configSystem = configSystemService.findByKey(keyFind);
    String saveDirectory = configSystem.getConfigText() + yearInString;

    //        File file = new File(saveDirectory + File.separator + convertNameAndTypeFile(fileUpload.getOriginalFilename(), numberTicket));
    //        System.out.println("file: "+file);
    //        file.delete();
    if (fileUpload != null && fileUpload.getSize() > 0) {
        File files = new File(saveDirectory + File.separator
                + convertNameAndTypeFile(fileUpload.getOriginalFilename(), numberTicket));
        if (!files.exists()) {
            files.mkdirs();/*w ww.  j a  v  a 2 s.  co m*/
        }
        if (!numberTicket.equals("")) {
            fileUpload.transferTo(files);
        }

    }

    // returns to the view "Result"
}

From source file:com.jkthome.cmm.web.JkthomeMultipartResolver.java

/**
 * multipart?  parsing? .// ww  w.  j  ava 2s  .  com
 */
@SuppressWarnings("rawtypes")
@Override
protected MultipartParsingResult parseFileItems(List fileItems, String encoding) {

    //? 3.0  
    MultiValueMap<String, MultipartFile> multipartFiles = new LinkedMultiValueMap<String, MultipartFile>();
    Map<String, String[]> multipartParameters = new HashMap<String, String[]>();

    // Extract multipart files and multipart parameters.
    for (Iterator<?> it = fileItems.iterator(); it.hasNext();) {
        FileItem fileItem = (FileItem) it.next();

        if (fileItem.isFormField()) {

            String value = null;
            if (encoding != null) {
                try {
                    value = fileItem.getString(encoding);
                } catch (UnsupportedEncodingException ex) {
                    LOGGER.warn(
                            "Could not decode multipart item '{}' with encoding '{}': using platform default",
                            fileItem.getFieldName(), encoding);
                    value = fileItem.getString();
                }
            } else {
                value = fileItem.getString();
            }
            String[] curParam = (String[]) multipartParameters.get(fileItem.getFieldName());
            if (curParam == null) {
                // simple form field
                multipartParameters.put(fileItem.getFieldName(), new String[] { value });
            } else {
                // array of simple form fields
                String[] newParam = StringUtils.addStringToArray(curParam, value);
                multipartParameters.put(fileItem.getFieldName(), newParam);
            }
        } else {

            if (fileItem.getSize() > 0) {
                // multipart file field
                CommonsMultipartFile file = new CommonsMultipartFile(fileItem);

                //? 3.0 ? API? 
                List<MultipartFile> fileList = new ArrayList<MultipartFile>();
                fileList.add(file);

                if (multipartFiles.put(fileItem.getName(), fileList) != null) { // CHANGED!!
                    throw new MultipartException("Multiple files for field name [" + file.getName()
                            + "] found - not supported by MultipartResolver");
                }
                LOGGER.debug(
                        "Found multipart file [{}] of size {} bytes with original filename [{}], stored {}",
                        file.getName(), file.getSize(), file.getOriginalFilename(),
                        file.getStorageDescription());
            }

        }
    }

    return new MultipartParsingResult(multipartFiles, multipartParameters, null);
}

From source file:egovframework.com.cmm.web.EgovMultipartResolver.java

/**
 * multipart?  parsing? .//from www.j a  v  a  2s  .c  o m
 */
@SuppressWarnings("unchecked")
@Override
protected MultipartParsingResult parseFileItems(List fileItems, String encoding) {

    //? 3.0  
    MultiValueMap<String, MultipartFile> multipartFiles = new LinkedMultiValueMap<String, MultipartFile>();
    Map<String, String[]> multipartParameters = new HashMap<String, String[]>();

    // Extract multipart files and multipart parameters.
    for (Iterator it = fileItems.iterator(); it.hasNext();) {
        FileItem fileItem = (FileItem) it.next();

        if (fileItem.isFormField()) {

            String value = null;
            if (encoding != null) {
                try {
                    value = fileItem.getString(encoding);
                } catch (UnsupportedEncodingException ex) {
                    if (logger.isWarnEnabled()) {
                        logger.warn("Could not decode multipart item '" + fileItem.getFieldName()
                                + "' with encoding '" + encoding + "': using platform default");
                    }
                    value = fileItem.getString();
                }
            } else {
                value = fileItem.getString();
            }
            String[] curParam = (String[]) multipartParameters.get(fileItem.getFieldName());
            if (curParam == null) {
                // simple form field
                multipartParameters.put(fileItem.getFieldName(), new String[] { value });
            } else {
                // array of simple form fields
                String[] newParam = StringUtils.addStringToArray(curParam, value);
                multipartParameters.put(fileItem.getFieldName(), newParam);
            }
        } else {

            if (fileItem.getSize() > 0) {
                // multipart file field
                CommonsMultipartFile file = new CommonsMultipartFile(fileItem);

                //? 3.0 ? API? 
                List<MultipartFile> fileList = new ArrayList<MultipartFile>();
                fileList.add(file);

                if (multipartFiles.put(fileItem.getName(), fileList) != null) { // CHANGED!!
                    throw new MultipartException("Multiple files for field name [" + file.getName()
                            + "] found - not supported by MultipartResolver");
                }
                if (logger.isDebugEnabled()) {
                    logger.debug("Found multipart file [" + file.getName() + "] of size " + file.getSize()
                            + " bytes with original filename [" + file.getOriginalFilename() + "], stored "
                            + file.getStorageDescription());
                }
            }

        }
    }

    return new MultipartParsingResult(multipartFiles, multipartParameters, null);
}