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:de.yaio.services.metaextract.server.controller.MetaExtractController.java

/** 
 * extract metadata from the uploaded file
 * @param uploadFile             the file to extract metadata from
 * @param lang                   the prevered lang to parse (OCR)
 * @return                       the extracted metadata
 * @throws IOException           possible
 *///from w ww  .j  a va 2  s  . c  om
@RequestMapping(method = RequestMethod.POST, value = "/getByFile")
public @ResponseBody ExtractedMetaData getByFile(@RequestParam("file") MultipartFile uploadFile,
        @RequestParam("lang") String lang) throws IOException, ExtractorException {
    return metaExtractFacade.extractMetaData(uploadFile.getInputStream(), uploadFile.getOriginalFilename(),
            lang);
}

From source file:com.opencart.controller.ProductController.java

@RequestMapping(value = "/product/upload", method = RequestMethod.POST)
public @ResponseBody ModelAndView handleFileUpload(@RequestParam("id") String id,
        @RequestParam("file") MultipartFile image, HttpServletRequest request) {
    if (!image.isEmpty()) {
        try {// w  w  w.java  2  s  .co  m
            File file = new File("c:/uploads/products/" + id + "/" + image.getOriginalFilename());

            FileUtils.writeByteArrayToFile(file, image.getBytes());
            Product product = productService.getById(Long.parseLong(id));
            product.setImg(file.getName());
            productService.update(product);

            List<Product> products = productService.list();
            ModelAndView mv = new ModelAndView("admin/product", "products", products);
            return mv;

        } catch (Exception e) {
            ModelAndView mv = new ModelAndView("admin/addProductImage");
            mv.addObject("id", id);
            return mv;
        }
    } else {
        ModelAndView mv = new ModelAndView("admin/addProductImage");
        mv.addObject("id", id);
        return mv;
    }
}

From source file:hu.bme.iit.quiz.service.QuizServiceImpl.java

@Override
public String validateAndCreateQuizForUserFromFile(MultipartFile file, String quizName, String loginName) {
    String originalFileName = file.getOriginalFilename();
    if (!file.isEmpty()) {
        try {/*from w  w w  .j  a va2s. com*/
            byte[] bytes = file.getBytes();

            //Only XML files, no mime check, basic check
            if (!file.getOriginalFilename().toLowerCase().endsWith(".xml")) {
                return "You failed to upload " + originalFileName + " because it's not an XML file.";
            }

            // Creating the directory to store file
            String rootPath = System.getProperty("catalina.home");
            File dir = new File(rootPath + File.separator + "tmpFiles");
            if (!dir.exists()) {
                dir.mkdirs();
            }

            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-mm-dd-HH-mm-ss");
            Date now = new Date();
            String innerFileLocation = dateFormat.format(now) + "_" + originalFileName;

            // Create the file on server
            File serverFile = new File(dir.getAbsolutePath() + File.separator + innerFileLocation);
            BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(serverFile));
            stream.write(bytes);
            stream.close();

            //Persist it in db
            Quiz quiz = new Quiz();
            quiz.setName(quizName);
            quiz.setBlobdata(bytes);
            quiz.setLocation(innerFileLocation);
            quiz.setUploaded(new Date());
            quiz.setInnerkey(UUID.randomUUID().toString());
            quiz.setOwner(userDAO.getUser(loginName));

            if (getQuizDataFromXML(quiz) != null) {
                quizDAO.addQuiz(quiz);
            } else {
                return "Invalid XML file!";
            }

            logger.info("XML file uploaded: " + originalFileName);
            return "You successfully uploaded '" + originalFileName + "'";
        } catch (Exception e) {
            logger.error(e);
            e.printStackTrace();
            return "You failed to upload " + originalFileName + " => " + e.getMessage();
        }
    } else {
        return "You failed to upload " + originalFileName + " because the file was empty.";
    }
}

From source file:ee.sk.hwcrypto.demo.controller.SigningController.java

@RequestMapping(value = "/upload", method = RequestMethod.POST)
public Result handleUpload(@RequestParam MultipartFile file) {
    log.debug("Handling file upload for file " + file.getOriginalFilename());
    try {//from w w  w.  j  a  va  2  s.c  om
        fileManager.setUploadedFile(new UploadedFile(file));
        return Result.resultOk();
    } catch (IOException e) {
        log.error("Error reading bytes from uploaded file " + file.getOriginalFilename(), e);
    }
    return Result.resultUploadingError();
}

From source file:com.epam.ta.reportportal.ws.controller.impl.LogController.java

/**
 * Tries to find request part or file with specified name in multipart files
 * map./*www  . j  a v a2s . c o m*/
 *
 * @param filename
 * @param files
 * @return
 */
private MultipartFile findByFileName(String filename, Map<String, MultipartFile> files) {
    /* Request part name? */
    if (files.containsKey(filename)) {
        return files.get(filename);
    }
    /* Filename? */
    for (MultipartFile file : files.values()) {
        if (filename.equals(file.getOriginalFilename())) {
            return file;
        }
    }
    return null;
}

From source file:de.blizzy.documentr.web.attachment.AttachmentController.java

private void saveAttachmentInternal(String projectName, String branchName, String pagePath, MultipartFile file,
        Authentication authentication) throws IOException {

    log.debug("saving attachment: {}", file.getOriginalFilename()); //$NON-NLS-1$

    byte[] data = IOUtils.toByteArray(file.getInputStream());
    String contentType = servletContext.getMimeType(file.getOriginalFilename());
    if (StringUtils.isBlank(contentType)) {
        contentType = DocumentrConstants.DEFAULT_MIME_TYPE;
    }/*from w  ww .j  a  va  2 s.  co  m*/
    Page attachment = Page.fromData(data, contentType);
    pagePath = Util.toRealPagePath(pagePath);
    User user = userStore.getUser(authentication.getName());
    pageStore.saveAttachment(projectName, branchName, pagePath, file.getOriginalFilename(), attachment, user);
}

From source file:org.spirit.spring.handler.BotListAdminHandler.java

public BotListDocFileMetadata uploadDocFile(HttpServletRequest request, Object form)
        throws IllegalStateException, IOException {

    BotListDocFileMetadata metadata = null;
    BotListDocFileForm docFile = (BotListDocFileForm) form;
    if (docFile.getUploadFilenameFirst() != null) {
        MultipartFile file = docFile.getUploadFilenameFirst();
        String filename = file.getOriginalFilename();
        if (filename.toLowerCase().endsWith(".txt")) {
            metadata = this.uploadCurFile(request, form, file);
        } else {//from w  w w  .  j  av  a 2 s  .c om
            System.out.println("ERR: invalid upload");
        }
    }

    return metadata;
}

From source file:com.epam.ta.reportportal.ws.controller.impl.LogController.java

private Map<String, MultipartFile> getUploadedFiles(HttpServletRequest request) {
    Map<String, MultipartFile> uploadedFiles = new HashMap<>();
    if (request instanceof MultipartHttpServletRequest) {
        MultiValueMap<String, MultipartFile> multiFileMap = (((MultipartHttpServletRequest) request))
                .getMultiFileMap();//from   w ww . j a  v  a  2 s.  co  m
        for (List<MultipartFile> multipartFiles : multiFileMap.values()) {
            for (MultipartFile file : multipartFiles) {
                uploadedFiles.put(file.getOriginalFilename(), file);
            }
        }
    }
    return uploadedFiles;
}

From source file:no.dusken.aranea.admin.control.ImageUploadController.java

@RequestMapping(value = "/imageUpload/uploadFile.do", method = RequestMethod.POST)
public @ResponseBody String upload(@RequestParam MultipartFile file) throws IOException {
    File file1 = new File(workDir, file.getOriginalFilename());
    file.transferTo(file1);// ww w .  j  ava2 s .  c  o  m
    file1.deleteOnExit();
    return "SUCCESS";
}

From source file:org.activiti.app.rest.editor.AbstractModelsResource.java

public ModelRepresentation importProcessModel(HttpServletRequest request, MultipartFile file) {

    String fileName = file.getOriginalFilename();
    if (fileName != null && (fileName.endsWith(".bpmn") || fileName.endsWith(".bpmn20.xml"))) {
        try {/*  ww  w  .  j  av a 2s .c  o m*/
            XMLInputFactory xif = XmlUtil.createSafeXmlInputFactory();
            InputStreamReader xmlIn = new InputStreamReader(file.getInputStream(), "UTF-8");
            XMLStreamReader xtr = xif.createXMLStreamReader(xmlIn);
            BpmnModel bpmnModel = bpmnXmlConverter.convertToBpmnModel(xtr);
            if (CollectionUtils.isEmpty(bpmnModel.getProcesses())) {
                throw new BadRequestException("No process found in definition " + fileName);
            }

            if (bpmnModel.getLocationMap().size() == 0) {
                BpmnAutoLayout bpmnLayout = new BpmnAutoLayout(bpmnModel);
                bpmnLayout.execute();
            }

            ObjectNode modelNode = bpmnJsonConverter.convertToJson(bpmnModel);

            org.activiti.bpmn.model.Process process = bpmnModel.getMainProcess();
            String name = process.getId();
            if (StringUtils.isNotEmpty(process.getName())) {
                name = process.getName();
            }
            String description = process.getDocumentation();

            ModelRepresentation model = new ModelRepresentation();
            model.setKey(process.getId());
            model.setName(name);
            model.setDescription(description);
            model.setModelType(AbstractModel.MODEL_TYPE_BPMN);
            Model newModel = modelService.createModel(model, modelNode.toString(),
                    SecurityUtils.getCurrentUserObject());
            return new ModelRepresentation(newModel);

        } catch (BadRequestException e) {
            throw e;

        } catch (Exception e) {
            logger.error("Import failed for " + fileName, e);
            throw new BadRequestException(
                    "Import failed for " + fileName + ", error message " + e.getMessage());
        }
    } else {
        throw new BadRequestException(
                "Invalid file name, only .bpmn and .bpmn20.xml files are supported not " + fileName);
    }
}