Example usage for org.springframework.web.multipart MultipartFile getOriginalFilename

List of usage examples for org.springframework.web.multipart MultipartFile getOriginalFilename

Introduction

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

Prototype

@Nullable
String getOriginalFilename();

Source Link

Document

Return the original filename in the client's filesystem.

Usage

From source file:data.repository.pragma.DataObjectController.java

@RequestMapping("/DO/update/data")
@ResponseBody//from w w w. j av  a2  s .  co m
public MessageResponse setData(@RequestParam(value = "ID", required = true) String id,
        @RequestParam(value = "data", required = true) MultipartFile file) {
    // Connect to MongoDB and set metadata as curation purposes
    // Return a new document ID

    try {
        // Get original Grid FS file
        GridFSDBFile doc = Staging_repository.findDOByID(id);

        // Ingest multipart file into inputstream
        byte[] byteArr = file.getBytes();
        InputStream inputStream = new ByteArrayInputStream(byteArr);
        String file_name = file.getOriginalFilename();
        String content_type = file.getContentType();

        // Push back updated DO to MongoDB and get a new doc ID
        String updated_id = Staging_repository.addDO(inputStream, file_name, content_type, doc.getMetaData());
        MessageResponse response = new MessageResponse(true, updated_id);
        return response;
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        MessageResponse response = new MessageResponse(false, null);
        return response;
    }
}

From source file:cn.mk.ndms.modules.lease.web.controller.LeaseController.java

@RequestMapping(value = "upload", method = RequestMethod.POST)
@ResponseBody/*from w  w w . j  a  v  a2  s. com*/
public AjaxBean upload(HttpServletRequest request, HttpServletResponse response) throws IOException {
    try {
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
                request.getSession().getServletContext());
        if (multipartResolver.isMultipart(request)) {
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
            Iterator<String> iter = multiRequest.getFileNames();
            while (iter.hasNext()) {
                MultipartFile file = multiRequest.getFile((String) iter.next());
                if (file != null) {
                    String fileName = file.getOriginalFilename();
                    String path1 = Thread.currentThread().getContextClassLoader().getResource("").getPath()
                            + "file" + File.separator;
                    //  ???
                    String path2 = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + fileName;
                    String path = path1 + path2;
                    File localFile = new File(path);
                    file.transferTo(localFile);
                    Lease lease = leaseService.findOne(request.getParameter("id"));
                    lease.setFilePath(path2);
                    leaseService.update(lease);
                }
            }
        }
        return AjaxBean.getInstance("success");
    } catch (Exception ex) {
        return AjaxBean.getInstance("error", ex.getMessage());
    }
}

From source file:com.qcadoo.mes.cmmsMachineParts.controller.MachinePartMultiUploadController.java

@ResponseBody
@RequestMapping(value = "/multiUploadFiles", method = RequestMethod.POST)
public void upload(MultipartHttpServletRequest request, HttpServletResponse response) {
    Long part = Long.parseLong(request.getParameter("partId"));
    Entity technology = dataDefinitionService
            .get(BasicConstants.PLUGIN_IDENTIFIER, BasicConstants.MODEL_PRODUCT).get(part);
    DataDefinition attachmentDD = dataDefinitionService.get("cmmsMachineParts", "machinePartAttachment");

    Iterator<String> itr = request.getFileNames();
    MultipartFile mpf = null;

    while (itr.hasNext()) {

        mpf = request.getFile(itr.next());

        String path = "";
        try {// www  .ja  v a 2 s.c o m
            path = fileService.upload(mpf);
        } catch (IOException e) {
            logger.error("Unable to upload attachment.", e);
        }
        if (exts.contains(Files.getFileExtension(path).toUpperCase())) {
            Entity atchment = attachmentDD.create();
            atchment.setField(TechnologyAttachmentFields.ATTACHMENT, path);
            atchment.setField(TechnologyAttachmentFields.NAME, mpf.getOriginalFilename());
            atchment.setField("product", technology);
            atchment.setField(TechnologyAttachmentFields.EXT, Files.getFileExtension(path));
            BigDecimal fileSize = new BigDecimal(mpf.getSize(), numberService.getMathContext());
            BigDecimal divider = new BigDecimal(1024, numberService.getMathContext());
            BigDecimal size = fileSize.divide(divider, L_SCALE, BigDecimal.ROUND_HALF_UP);
            atchment.setField(TechnologyAttachmentFields.SIZE, size);
            atchment = attachmentDD.save(atchment);
            atchment.isValid();
        }
    }
}

From source file:com.courtalon.gigaMvcGalerie.web.ImageController.java

@RequestMapping(value = "/images/data", method = RequestMethod.POST, produces = "application/json")
@ResponseBody//from   w ww.  jav  a  2 s  . c om
@JsonView(AssetOnly.class)
public Image upload(@RequestParam("file") MultipartFile file,
        @RequestParam("licenseId") Optional<Integer> licenseId,
        @RequestParam("sourceId") Optional<Integer> sourceId,
        @RequestParam("tagsId") Optional<List<Integer>> tagsId) {
    Image img = null;
    try {
        img = getImageRepository()
                .save(new Image(0, file.getOriginalFilename(), "", new Date(), file.getOriginalFilename(),
                        file.getContentType(), file.getSize(), DigestUtils.md5Hex(file.getInputStream())));

        getImageRepository().saveImageFile(img.getId(), file.getInputStream());
        img.addTag(getTagRepository().findByLibelleAndSystemTag(TagRepository.UPLOADED, true));
        img.setLicense(getLicenseTypeRepository().findOne(licenseId.orElse(LicenseType.NO_LICENSE_ID)));
        img.setSource(getAssetSourceRepository().findOne(sourceId.orElse(AssetSource.UNKOWN_SOURCE_ID)));
        final Image image = img;
        if (tagsId.isPresent()) {
            tagsId.get().forEach(id -> image.addTag(getTagRepository().findByIdAndSystemTag(id, false)));
        }
        getImageRepository().save(img);

    } catch (IOException e) {
        log.error(e);
        throw new HttpClientErrorException(HttpStatus.INTERNAL_SERVER_ERROR, "could not save uploaded image");
    }
    return img;
}

From source file:com.qcadoo.mes.cmmsMachineParts.controller.MaintenanceEventMultiUploadController.java

@ResponseBody
@RequestMapping(value = "/multiUploadFilesForEvent", method = RequestMethod.POST)
public void upload(MultipartHttpServletRequest request, HttpServletResponse response) {
    Long eventId = Long.parseLong(request.getParameter("eventId"));
    Entity event = dataDefinitionService
            .get(CmmsMachinePartsConstants.PLUGIN_IDENTIFIER, CmmsMachinePartsConstants.MODEL_MAINTENANCE_EVENT)
            .get(eventId);//w w w  .  j a  v  a2 s  .co m
    DataDefinition attachmentDD = dataDefinitionService.get("cmmsMachineParts", "eventAttachment");

    Iterator<String> itr = request.getFileNames();
    MultipartFile mpf = null;

    while (itr.hasNext()) {

        mpf = request.getFile(itr.next());

        String path = "";
        try {
            path = fileService.upload(mpf);
        } catch (IOException e) {
            logger.error("Unable to upload attachment.", e);
        }
        if (exts.contains(Files.getFileExtension(path).toUpperCase())) {
            Entity atchment = attachmentDD.create();
            atchment.setField(TechnologyAttachmentFields.ATTACHMENT, path);
            atchment.setField(TechnologyAttachmentFields.NAME, mpf.getOriginalFilename());
            atchment.setField("maintenanceEvent", event);
            atchment.setField(TechnologyAttachmentFields.EXT, Files.getFileExtension(path));
            BigDecimal fileSize = new BigDecimal(mpf.getSize(), numberService.getMathContext());
            BigDecimal divider = new BigDecimal(1024, numberService.getMathContext());
            BigDecimal size = fileSize.divide(divider, L_SCALE, BigDecimal.ROUND_HALF_UP);
            atchment.setField(TechnologyAttachmentFields.SIZE, size);
            atchment = attachmentDD.save(atchment);
            atchment.isValid();
        }
    }
}

From source file:com.qcadoo.mes.technologies.controller.TechnologyMultiUploadController.java

@ResponseBody
@RequestMapping(value = "/multiUploadFiles", method = RequestMethod.POST)
public void upload(MultipartHttpServletRequest request, HttpServletResponse response) {
    Long technologyId = Long.parseLong(request.getParameter("techId"));
    Entity technology = dataDefinitionService
            .get(TechnologiesConstants.PLUGIN_IDENTIFIER, TechnologiesConstants.MODEL_TECHNOLOGY)
            .get(technologyId);/*  www  .j av  a  2  s . com*/
    DataDefinition attachmentDD = dataDefinitionService.get(TechnologiesConstants.PLUGIN_IDENTIFIER,
            TechnologiesConstants.MODEL_TECHNOLOGY_ATTACHMENT);

    Iterator<String> itr = request.getFileNames();
    MultipartFile mpf = null;

    while (itr.hasNext()) {

        mpf = request.getFile(itr.next());

        String path = "";
        try {
            path = fileService.upload(mpf);
        } catch (IOException e) {
            logger.error("Unable to upload attachment.", e);
        }
        if (exts.contains(Files.getFileExtension(path).toUpperCase())) {
            Entity atchment = attachmentDD.create();
            atchment.setField(TechnologyAttachmentFields.ATTACHMENT, path);
            atchment.setField(TechnologyAttachmentFields.NAME, mpf.getOriginalFilename());
            atchment.setField(TechnologyAttachmentFields.TECHNOLOGY, technology);
            atchment.setField(TechnologyAttachmentFields.EXT, Files.getFileExtension(path));
            BigDecimal fileSize = new BigDecimal(mpf.getSize(), numberService.getMathContext());
            BigDecimal divider = new BigDecimal(1024, numberService.getMathContext());
            BigDecimal size = fileSize.divide(divider, L_SCALE, BigDecimal.ROUND_HALF_UP);
            atchment.setField(TechnologyAttachmentFields.SIZE, size);
            attachmentDD.save(atchment);
        }
    }
}

From source file:com.qcadoo.mes.basic.controllers.WorkstationMultiUploadController.java

@ResponseBody
@RequestMapping(value = "/multiUploadFiles", method = RequestMethod.POST)
public void upload(MultipartHttpServletRequest request, HttpServletResponse response) {
    Long workstationId = Long.parseLong(request.getParameter("techId"));
    Entity workstation = dataDefinitionService
            .get(BasicConstants.PLUGIN_IDENTIFIER, BasicConstants.MODEL_WORKSTATION).get(workstationId);
    DataDefinition attachmentDD = dataDefinitionService.get(BasicConstants.PLUGIN_IDENTIFIER,
            BasicConstants.MODEL_WORKSTATION_ATTACHMENT);

    Iterator<String> itr = request.getFileNames();
    MultipartFile mpf = null;

    while (itr.hasNext()) {

        mpf = request.getFile(itr.next());

        String path = "";
        try {//  ww w .  ja v a2s  .  co m
            path = fileService.upload(mpf);
        } catch (IOException e) {
            logger.error("Unable to upload attachment.", e);
        }
        if (exts.contains(Files.getFileExtension(path).toUpperCase())) {
            Entity atchment = attachmentDD.create();
            atchment.setField(WorkstationAttachmentFields.ATTACHMENT, path);
            atchment.setField(WorkstationAttachmentFields.NAME, mpf.getOriginalFilename());
            atchment.setField(WorkstationAttachmentFields.WORKSTATION, workstation);
            atchment.setField(WorkstationAttachmentFields.EXT, Files.getFileExtension(path));
            BigDecimal fileSize = new BigDecimal(mpf.getSize(), numberService.getMathContext());
            BigDecimal divider = new BigDecimal(1024, numberService.getMathContext());
            BigDecimal size = fileSize.divide(divider, L_SCALE, BigDecimal.ROUND_HALF_UP);
            atchment.setField(WorkstationAttachmentFields.SIZE, size);
            attachmentDD.save(atchment);
        }
    }
}

From source file:com.cisco.ca.cstg.pdi.services.ConfigurationServiceImpl.java

@Override
public void validateAndCopyFile(MultipartFile file, Integer projectId) throws IOException {
    String copyFolderPath = null;
    String projectPath = null;//  w w  w. j a va  2s .  com
    boolean status = false;
    File tempFile = null;

    if (file.getOriginalFilename().toLowerCase().matches(".*\\.zip$|.*\\.xml$")) {

        copyFolderPath = Util.getPdiConfFolderPath(projectDetailsService.fetchProjectDetails(projectId));
        projectPath = Util.getPdiConfDataFolderPath(projectDetailsService.fetchProjectDetails(projectId));
        // if exists delete previously created folder
        deletePreviousUcsData(projectId);
        // create project folder
        Util.createFolder(projectPath);

        tempFile = new File(copyFolderPath + File.separator + file.getOriginalFilename());
        file.transferTo(tempFile);

        if (tempFile.getName().toLowerCase().matches(".*\\.zip$") && validateZipFile(tempFile)) {
            copyZipFile(tempFile, projectPath);
            status = true;
        } else {
            copyXmlFile(tempFile, projectPath);
            status = true;
        }

        if (!status) {
            throw new FileExistsException();
        }
    }
}

From source file:com.shouwy.series.web.control.admin.AdminSerieController.java

@RequestMapping(value = "/admin/series/modif/validate", method = RequestMethod.POST)
public ModelAndView validate(@RequestParam(value = "image", required = false) MultipartFile image,
        @RequestParam(value = "nom", required = false) String name,
        @RequestParam(value = "synopsis", required = false) String synopsis,
        @RequestParam(value = "type", required = false) Integer idType,
        @RequestParam(value = "etat", required = false) Integer idEtat,
        @RequestParam(value = "etatPerso", required = false) Integer idEtatPerso,
        @RequestParam(value = "id", required = true) Integer id) {

    Series s = seriesDao.getById(id);/* w  w w  . j  a  va  2s.  c om*/
    String filename = image.getOriginalFilename();

    s.setNom(name);
    s.setSynopsis(synopsis);
    s.setIdType(idType);
    s.setIdEtat(idEtat);
    s.setIdEtatPersonnel(idEtatPerso);

    seriesDao.update(s);
    return this.modif(s.getId());
}

From source file:it.geosolutions.opensdi.operations.FileBrowserOperationController.java

/**
 * Shows the list of files inside the selected folder after a file upload
 * /*  w w  w .j a  va  2  s  . co m*/
 * @param model
 * @return
 */
// @RequestMapping(value = "/files", method = RequestMethod.POST)
public String saveFileAndList(@ModelAttribute("uploadFile") FileUpload uploadFile, ModelMap model) {

    List<MultipartFile> files = uploadFile.getFiles();

    List<String> fileNames = new ArrayList<String>();

    HashMap<String, List<Operation>> availableOperations = getAvailableOperations();

    if (null != files && files.size() > 0) {
        for (MultipartFile multipartFile : files) {

            String fileName = multipartFile.getOriginalFilename();
            if (!"".equalsIgnoreCase(fileName)) {
                // Handle file content - multipartFile.getInputStream()
                try {
                    multipartFile.transferTo(new File(getRunTimeDir() + fileName));
                } catch (IllegalStateException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                fileNames.add(fileName);
            }
            LOGGER.debug(fileName);

        }
    }

    model.addAttribute("uploadedFiles", fileNames);
    model.addAttribute("accept", accept);
    FileBrowser fb = null;
    if (Boolean.TRUE.equals(this.showRunInformation)) {
        fb = new ExtendedFileBrowser();
        ((ExtendedFileBrowser) fb).setAvailableOperations(availableOperations);
        ((ExtendedFileBrowser) fb).setGeoBatchClient(geoBatchClient);
    } else {
        fb = new FileBrowser();
    }
    fb.setBaseDir(getRunTimeDir());
    fb.setRegex(fileRegex);
    fb.setScanDiretories(canNavigate);
    model.addAttribute("fileBrowser", fb);
    model.addAttribute("showRunInformation", showRunInformation);

    model.addAttribute("operations", availableOperations);

    model.addAttribute("context", operationJSP);
    ControllerUtils.setCommonModel(model);

    return "template";

}