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.company.project.web.controller.FileUploadController.java

@RequestMapping(value = "/doUpload", method = RequestMethod.POST)
public String handleFileUpload(HttpServletRequest request, @RequestParam CommonsMultipartFile[] fileUpload)
        throws Exception {

    if (fileUpload != null && fileUpload.length > 0) {
        for (CommonsMultipartFile aFile : fileUpload) {
            String fileName = null;
            if (!aFile.isEmpty()) {
                try {
                    fileName = aFile.getOriginalFilename();
                    byte[] bytes = aFile.getBytes();
                    BufferedOutputStream buffStream = new BufferedOutputStream(
                            new FileOutputStream(new File("D:/CX1/" + fileName)));
                    buffStream.write(bytes);
                    buffStream.close();/*  ww  w.ja va2s .  c  o m*/
                    System.out.println("You have successfully uploaded " + fileName);
                } catch (Exception e) {
                    System.out.println("You failed to upload " + fileName + ": " + e.getMessage());
                }
            } else {
                System.out.println("Unable to upload. File is empty.");
            }

            System.out.println("Saving file: " + aFile.getOriginalFilename());

            aFile.getOriginalFilename();
            aFile.getBytes();

        }
    }

    return "admin";
}

From source file:com.company.project.web.controller.FileUploadController.java

@RequestMapping(value = "/asyncUpload", method = RequestMethod.POST/*, produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.MULTIPART_FORM_DATA_VALUE*/)
@ResponseBody// w ww  .j a  va2 s  .c om
public ResponseEntity<String> asyncFileUpload(HttpServletRequest request,
        @RequestParam CommonsMultipartFile[] fileUpload) throws Exception {

    if (fileUpload != null && fileUpload.length > 0) {
        for (CommonsMultipartFile aFile : fileUpload) {
            String fileName = null;
            if (!aFile.isEmpty()) {
                try {
                    fileName = aFile.getOriginalFilename();
                    byte[] bytes = aFile.getBytes();
                    BufferedOutputStream buffStream = new BufferedOutputStream(
                            new FileOutputStream(new File("D:/CX1/" + fileName)));
                    buffStream.write(bytes);
                    buffStream.close();
                    System.out.println("You have successfully uploaded " + fileName);
                } catch (Exception e) {
                    System.out.println("You failed to upload " + fileName + ": " + e.getMessage());
                }
            } else {
                System.out.println("Unable to upload. File is empty.");
            }

            System.out.println("Saving file: " + aFile.getOriginalFilename());

            aFile.getOriginalFilename();
            aFile.getBytes();

        }
    }

    return new ResponseEntity<>("success", HttpStatus.OK);
}

From source file:com.br.uepb.controller.MedicaoController.java

@RequestMapping(value = "/home/medicao.html", method = RequestMethod.POST)
public ModelAndView medicaoPost(HttpServletRequest request, Model model,
        @ModelAttribute("uploadItem") UploadItem uploadItem) {

    String login = request.getSession().getAttribute("login").toString();

    SessaoBusiness sessao = GerenciarSessaoBusiness.getSessaoBusiness(login);
    MedicoesBusiness medicoesBusiness = new MedicoesBusiness();
    LoginDomain loginDomain = sessao.getLoginDomain();

    ModelAndView modelAndView = new ModelAndView();
    String mensagem = "";
    String status = "";

    @SuppressWarnings("deprecation")
    String uploadRootPath = request.getRealPath(File.separator);

    File uploadRootDir = new File(uploadRootPath);

    // Cria o diretrio se no existir
    if (!uploadRootDir.exists()) {
        uploadRootDir.mkdirs();//from   w ww.j  a va2  s  .c  om
    }
    CommonsMultipartFile fileData = uploadItem.getFileData();

    // Nome do arquivo cliente
    String name = fileData.getOriginalFilename();

    if (name != null && name.length() > 0) {
        try {
            // Create the file on server
            File serverFile = new File(uploadRootDir.getAbsolutePath() + File.separator + name);

            BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(serverFile));
            stream.write(fileData.getBytes());
            stream.close();
            // Salvou o arquivo xml

            String tipo_dispositivo = uploadItem.getTipo_dispositivo();
            String arquivo = serverFile.toString();

            if (tipo_dispositivo.equals("2")) { // oximetro
                modelAndView.addObject("tipoDispositivo", 2);
                if (medicoesBusiness.medicaoOximetro(arquivo, login)) {
                    //medicoesBusiness.medicaoOximetro(arquivo);
                    mensagem = "Medio Oximetro cadastrada com sucesso!";
                    status = "0";

                    MedicaoOximetroDomain oximetro = medicoesBusiness
                            .listaUltimaMedicaoOximetro(loginDomain.getPaciente().getId());
                    modelAndView.addObject("oximetro", oximetro);
                    modelAndView.addObject("balanca", null);
                    modelAndView.addObject("pressao", null);
                    modelAndView.addObject("icg", null);

                } else {
                    mensagem = "Erro ao cadastrar Oximetro arquivo XML!";
                    status = "1";
                }

            } else if (tipo_dispositivo.equals("1")) { // balanca
                modelAndView.addObject("tipoDispositivo", 1);
                if (medicoesBusiness.medicaoBalanca(arquivo, login)) {
                    mensagem = "Medio Balana cadastrada com sucesso!";
                    status = "0";

                    MedicaoBalancaDomain balanca = medicoesBusiness
                            .listaUltimaMedicaoBalanca(loginDomain.getPaciente().getId());
                    modelAndView.addObject("oximetro", null);
                    modelAndView.addObject("balanca", balanca);
                    modelAndView.addObject("pressao", null);
                    modelAndView.addObject("icg", null);
                } else {
                    mensagem = "Erro ao cadastrar Balana arquivo XML!";
                    status = "1";
                }

            } else if (tipo_dispositivo.equals("3")) { // pressao
                modelAndView.addObject("tipoDispositivo", 3);
                if (medicoesBusiness.medicaoPressao(arquivo, login)) {
                    mensagem = "Medio Presso cadastrada com sucesso!";
                    status = "0";

                    MedicaoPressaoDomain pressao = medicoesBusiness
                            .listaUltimaMedicaoPressao(loginDomain.getPaciente().getId());
                    modelAndView.addObject("oximetro", null);
                    modelAndView.addObject("balanca", null);
                    modelAndView.addObject("pressao", pressao);
                    modelAndView.addObject("icg", null);
                } else {
                    mensagem = "Erro ao cadastrar Presso arquivo XML!";
                    status = "1";
                }

            } else if (tipo_dispositivo.equals("0")) { // icg
                modelAndView.addObject("tipoDispositivo", 0);
                if (medicoesBusiness.medicaoIcg(arquivo, login)) {
                    mensagem = "Medio ICG cadastrada com sucesso!";
                    status = "0";

                    MedicaoIcgDomain icg = medicoesBusiness
                            .listaUltimaMedicaoIcg(loginDomain.getPaciente().getId());
                    modelAndView.addObject("oximetro", null);
                    modelAndView.addObject("balanca", null);
                    modelAndView.addObject("pressao", null);
                    modelAndView.addObject("icg", icg);

                } else {
                    mensagem = "Erro ao cadastrar ICG arquivo XML!";
                    status = "1";
                }
            } else {
                mensagem = "Erro ao cadastrar arquivo XML!";
                status = "1";
            }

        } catch (Exception e) {
            mensagem = "Erro ao cadastrar arquivo XML!";
            status = "1";
        }
    } else {
        mensagem = "O arquivo no foi informado ou est vazio";
        status = "1";
    }

    if (status == "1") {
        modelAndView.addObject("tipoDispositivo", null);
        modelAndView.addObject("oximetro", null);
        modelAndView.addObject("balanca", null);
        modelAndView.addObject("pressao", null);
        modelAndView.addObject("icg", null);
    }

    model.addAttribute("mensagem", mensagem);
    model.addAttribute("status", status);
    modelAndView.setViewName("home/medicao");
    return modelAndView;
}

From source file:com.ms.commons.summer.web.multipart.CommonsMultipartEngancedResolver.java

/**
 * @param value/*from   w  w w. j a  v  a 2 s .  c om*/
 */
private void cleanSingleFileItem(CommonsMultipartFile file) {

    if (logger.isDebugEnabled()) {
        logger.debug("Cleaning up multipart file [" + file.getName() + "] with original filename ["
                + file.getOriginalFilename() + "], stored " + file.getStorageDescription());
    }
    file.getFileItem().delete();
}

From source file:com.suntek.gztpb.controller.DriverLicenseController.java

@RequestMapping(value = "upload.htm", method = RequestMethod.POST) //
public String handleFormUpload(HttpServletRequest request, HttpServletResponse response) throws IOException {
    MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
    String inputName = request.getParameter("name");
    CommonsMultipartFile mFile = (CommonsMultipartFile) multipartRequest.getFile(inputName);

    if (!mFile.isEmpty()) {
        String path = this.servletContext.getRealPath("/picUpload/");
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
        String fileName = format.format(new Date()) + "_" + mFile.getOriginalFilename();
        File fold = new File(path);
        if (!fold.exists()) {
            fold.mkdir();/*from  w  w w .  ja  va 2s.  com*/
        }
        path = path + "\\" + fileName; // ?

        File file = new File(path); // 

        response.setContentType("text/html");
        response.setCharacterEncoding("utf-8");
        PrintWriter out = response.getWriter();

        try {
            mFile.getFileItem().write(file); // 
            out.write("<script>parent.callback(1,'" + fileName + "','" + inputName + "')</script>");
        } catch (Exception e) {
            logger.error(e.getMessage());
            out.write("<script>parent.callback(0)</script>");
        }
    }
    return null;
}

From source file:egovframework.asadal.asapro.com.cmm.web.AsaproEgovMultipartResolver.java

/**
 * multipart?  parsing? ./*from  w  w  w  .  j  ava 2  s  .c  om*/
 */
@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 (!AsaproEgovWebUtil.checkAllowUploadFileExt(file.getOriginalFilename()))
                    throw new MultipartException(" ? ? .");

                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);
}

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

public void handleFileUploadToPathTaget(CommonsMultipartFile fileUpload, String partDirectory, String fileName)
        throws Exception {

    //String saveDirectory = "D://file/report";
    String saveDirectory = partDirectory;
    if (fileUpload != null && fileUpload.getSize() > 0) {

        String newFileName = fileName;
        if (newFileName == null || newFileName == "") {
            newFileName = convertNameAndTypeFile(fileUpload.getOriginalFilename());
        }//from w w  w .j a va  2 s  .  c  om

        File files = new File(saveDirectory + File.separator + newFileName);
        if (!files.exists()) {
            files.mkdirs();
        }
        fileUpload.transferTo(files);
        System.out.println("save file at ");
    }
    System.out.println("SYSTEM ALEART UPLOAD FILE SUCCESSFUL");
}

From source file:org.toobsframework.pres.spring.multipart.MultipartController.java

protected MultipartParsingResult parseFileItems(List fileItems, String encoding, int IHateYouJuergenHoeller) {
    Map multipartFiles = new LinkedHashMap();
    Map multipartParameters = new LinkedHashMap();

    // Extract multipart files and multipart parameters.
    for (Iterator it = fileItems.iterator(); it.hasNext();) {
        FileItem fileItem = (FileItem) it.next();
        if (fileItem.isFormField()) {
            String value = null;/*from  www . ja v a2s. c  o m*/
            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 {
            // multipart file field
            CommonsMultipartFile file = new CommonsMultipartFile(fileItem);
            multipartFiles.put(file.getName(), file);
            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:com.gradecak.alfresco.simpless.MetadataManager.java

/**
 * handles only simple types (no associations ... complex types)
 * /*from   w  w w .  ja  va2 s.  c  om*/
 * any null properties will be removed from the node by calling nodeService.removeProperty, as
 * setting null is considered as a removal of the value
 * 
 * if a cm:content property is present than the value might be a file, a multipart, a ContentData
 * or a String. Otherwise the value must be <code>Serializable</code> However, before saving an
 * alfresco converter is executed on the vale for the given type repreented in the model
 * 
 * Any readonly properties will not be serialized/saved
 * 
 * return {@link SysBase} with converted values (did not check the repository) but without syncing
 * actions & aspects as we belongs to the same transaction and so the sync should be done after
 * the call to this method. As example we might consider behaviors that can change values of the
 * node
 */
public <T extends SysBase> T save(final T object) {
    Assert.notNull(object, "object must not be null");

    MetadataHolder holder = object.getMetadataHolder();
    Assert.notNull(holder, "the holder object must not be null");

    Map<QName, Serializable> allProps = holder.getPropertiesMap();

    // resolve unkown properties and put it all together
    Map<String, Serializable> unkwonProperties = object.getUnkwonProperties();
    for (Entry<String, Serializable> entry : unkwonProperties.entrySet()) {
        QName qname = QName.resolveToQName(serviceRegistry.getNamespaceService(), entry.getKey());
        allProps.put(qname, entry.getValue());
    }

    NodeRef toNode = object.getNodeRef();

    // works on latest alfresco versions. if
    // if (this.serviceRegistry.getCheckOutCheckInService().isCheckedOut(toNode)) {

    // works on all alfresco versions
    if (this.serviceRegistry.getCheckOutCheckInService().getWorkingCopy(toNode) != null) {
        if (LockStatus.LOCK_OWNER.equals(this.serviceRegistry.getLockService().getLockStatus(toNode))) {
            toNode = this.serviceRegistry.getCheckOutCheckInService().getWorkingCopy(toNode);
        }
    }

    Metadata properties = new Metadata();
    for (Entry<QName, Serializable> entry : allProps.entrySet()) {
        QName qname = entry.getKey();
        if (qname == null) {
            continue;
        }

        PropertyDefinition propertyDef = this.serviceRegistry.getDictionaryService().getProperty(qname);
        if (propertyDef == null) {
            continue;
        }

        if (holder.isReadOnlyProperty(qname)) {
            continue;
        }

        Serializable value = entry.getValue();

        if (value instanceof String[]) {
            // TODO: check if we need to handle props different than String[]
            value = ((String[]) value)[0];
        }

        DataTypeDefinition dataType = propertyDef.getDataType();
        if (DataTypeDefinition.CONTENT.equals(dataType.getName())) {

            if (toNode != null) {
                ContentWriter writer = this.serviceRegistry.getContentService().getWriter(toNode,
                        propertyDef.getName(), true);

                if (value instanceof CommonsMultipartFile) {
                    CommonsMultipartFile file = (CommonsMultipartFile) value;
                    writer.setMimetype(this.serviceRegistry.getMimetypeService()
                            .guessMimetype(file.getOriginalFilename()));
                    try {
                        writer.putContent(file.getInputStream());
                    } catch (IOException e) {
                        throw new ContentIOException("Could not write the file input stream", e);
                    }
                } else if (value instanceof File) {
                    File file = (File) value;
                    writer.setMimetype(this.serviceRegistry.getMimetypeService().guessMimetype(file.getName()));
                    writer.putContent(file);
                } else if (value instanceof String) {
                    writer.setMimetype("text/plain");
                    writer.putContent((String) value);
                } else if (value instanceof ContentData) {
                    properties.put(qname, (ContentData) value);
                } else {
                    if (value != null) {
                        throw new RuntimeException(
                                "Unhandled property of type d:content. Name : " + propertyDef.getName());
                    }
                }
            }
        } else {
            if (DataTypeDefinition.QNAME.equals(dataType.getName())) {
                if (value instanceof String && !StringUtils.hasText((String) value)) {
                    continue;
                }
            }

            Object convertedValue = converter.convert(dataType, value);
            if (convertedValue == null) {
                // TODO marked in order to verify this behavior
                // we remove the specific property as its value has been erased
                this.serviceRegistry.getNodeService().removeProperty(toNode, qname);
            } else {
                properties.put(qname, (Serializable) convertedValue);
                object.getMetadataHolder().setProperty(qname, (Serializable) convertedValue);
            }
        }
    }

    // assure to remove nodeRef property before saving
    properties.remove(ContentModel.PROP_NODE_REF);
    if (!properties.isEmpty()) {
        this.serviceRegistry.getNodeService().addProperties(toNode, properties);
    }

    syncAspectsAndActions(toNode, object);

    return object;
}

From source file:com.hp.avmon.agentless.service.AgentlessService.java

public String importAgentlessFile(HttpServletRequest request) throws IOException {

    String result = StringUtil.EMPTY;
    HashMap<String, ArrayList<Map<String, String>>> resultMap = new HashMap<String, ArrayList<Map<String, String>>>();
    ArrayList<Map<String, String>> files = new ArrayList<Map<String, String>>();
    Map<String, HashMap<String, List<String>>> map = new HashMap<String, HashMap<String, List<String>>>();

    MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
    //?/*from  w w  w  . ja  v  a2s  .c o  m*/
    String templatePath = Config.getInstance().getAgentlessfilesUploadPath();
    File dirPath = new File(templatePath);
    if (!dirPath.exists()) {
        dirPath.mkdirs();
    }
    Map<String, String> fileMap;
    try {
        for (Iterator it = multipartRequest.getFileNames(); it.hasNext();) {
            String fileName = (String) it.next();
            CommonsMultipartFile file = (CommonsMultipartFile) multipartRequest.getFile(fileName);
            if (file != null && file.getSize() != 0) {
                String sep = System.getProperty("file.separator");
                String importFilePath = dirPath + sep + file.getOriginalFilename();
                File uploadedFile = new File(importFilePath);
                FileCopyUtils.copy(file.getBytes(), uploadedFile);
                //??
                String importStatus = importRmpInstance(importFilePath);
                //boolean importStatus = false;
                String name = file.getOriginalFilename();
                fileMap = new HashMap<String, String>();

                if (importStatus.indexOf("success") > -1) {
                    fileMap.put("status", "success");
                    String[] s = importStatus.split(":");
                    fileMap.put("msg", "?" + s[1] + "" + s[2]);
                } else {
                    fileMap.put("status", "failed");
                    fileMap.put("msg", importStatus);
                }
                fileMap.put("url", "");
                fileMap.put("thumbnailUrl", "");
                fileMap.put("name", name);
                fileMap.put("type", "image/jpeg");
                fileMap.put("size", file.getSize() + "");
                fileMap.put("deleteUrl", "");
                fileMap.put("deleteType", "DELETE");
                files.add(fileMap);
            }
        }

    } catch (Exception e) {
        e.printStackTrace();
        logger.error(e);
    }
    resultMap.put("files", files);
    result = JackJson.fromObjectToJson(resultMap);
    logger.debug(result);
    return result;
}