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:cz.zcu.kiv.eegdatabase.webservices.rest.scenario.ScenarioServiceImpl.java

/**
 * {@inheritDoc}// w w  w. j a  v  a 2 s  .c o  m
 */
@Override
@Transactional
public int create(ScenarioData scenarioData, MultipartFile file)
        throws IOException, SAXException, ParserConfigurationException {
    Scenario scenario = new Scenario();
    scenario.setDescription(scenarioData.getDescription());
    scenario.setTitle(scenarioData.getScenarioName());
    scenario.setScenarioName(file.getOriginalFilename().replace(" ", "_"));
    scenario.setMimetype(scenarioData.getMimeType().toLowerCase().trim());

    //DB column size restriction
    if (scenario.getMimetype().length() > 30) {
        scenario.setMimetype("application/octet-stream");
    }

    ResearchGroup group = researchGroupDao.read(scenarioData.getResearchGroupId());
    scenario.setResearchGroup(group);
    Person owner = personDao.getLoggedPerson();
    scenario.setPerson(owner);

    scenario.setScenarioLength((int) file.getSize());

    scenario.setPrivateScenario(scenarioData.isPrivate());
    return scenarioDao.create(scenario);

}

From source file:pt.ist.fenix.ui.spring.PagesAdminService.java

@Atomic
protected GroupBasedFile addPostFile(MultipartFile attachment, MenuItem menuItem) throws IOException {
    GroupBasedFile f = new GroupBasedFile(attachment.getOriginalFilename(), attachment.getOriginalFilename(),
            attachment.getBytes(), AnyoneGroup.get());
    postForPage(menuItem.getPage()).getPostFiles().putFile(f);
    return f;//from   w  ww.  j  a  v a 2 s  .  c  om
}

From source file:com.glaf.template.web.springmvc.MxSystemTemplateController.java

@RequestMapping("/save")
public ModelAndView save(HttpServletRequest request, ModelMap modelMap) throws IOException {
    LoginContext loginContext = RequestUtils.getLoginContext(request);

    String templateId = request.getParameter("templateId");
    Template template = null;//from  w w  w.j  a  va  2  s .co  m
    if (StringUtils.isNotEmpty(templateId)) {
        template = templateService.getTemplate(templateId);
    }

    if (template == null) {
        template = new Template();
        template.setCreateBy(loginContext.getActorId());
    }

    MultipartHttpServletRequest req = (MultipartHttpServletRequest) request;
    Map<String, Object> paramMap = RequestUtils.getParameterMap(req);
    Tools.populate(template, paramMap);

    String nodeId = ParamUtils.getString(paramMap, "nodeId");
    if (nodeId != null) {

    }

    Map<String, MultipartFile> fileMap = req.getFileMap();
    Set<Entry<String, MultipartFile>> entrySet = fileMap.entrySet();
    for (Entry<String, MultipartFile> entry : entrySet) {
        MultipartFile mFile = entry.getValue();
        String filename = mFile.getOriginalFilename();
        if (mFile.getSize() > 0) {
            template.setFileSize(mFile.getSize());
            int fileType = 0;

            if (filename.endsWith(".java")) {
                fileType = 50;
                template.setContent(new String(mFile.getBytes()));
            } else if (filename.endsWith(".jsp")) {
                fileType = 51;
                template.setContent(new String(mFile.getBytes()));
            } else if (filename.endsWith(".ftl")) {
                fileType = 52;
                template.setLanguage("freemarker");
                template.setContent(new String(mFile.getBytes()));
            } else if (filename.endsWith(".vm")) {
                fileType = 54;
                template.setLanguage("velocity");
                template.setContent(new String(mFile.getBytes()));
            } else if (filename.endsWith(".xml")) {
                fileType = 60;
                template.setContent(new String(mFile.getBytes()));
            } else if (filename.endsWith(".htm") || filename.endsWith(".html")) {
                fileType = 80;
                template.setContent(new String(mFile.getBytes()));
            } else if (filename.endsWith(".js")) {
                fileType = 82;
                template.setContent(new String(mFile.getBytes()));
            } else if (filename.endsWith(".css")) {
                fileType = 84;
                template.setContent(new String(mFile.getBytes()));
            } else if (filename.endsWith(".txt")) {
                fileType = 85;
                template.setContent(new String(mFile.getBytes()));
            }

            template.setDataFile(filename);
            template.setFileType(fileType);
            template.setCreateDate(new Date());
            template.setData(mFile.getBytes());
            template.setLastModified(System.currentTimeMillis());
            template.setTemplateType(FileUtils.getFileExt(filename));
            break;
        }
    }

    templateService.saveTemplate(template);

    return this.list(request, modelMap);
}

From source file:me.utils.excel.ImportExcelme.java

/**
 * /*from   w w  w.j a v a 2 s.c  o m*/
 * @param file 
 * @param headerNum ???=?+1
 * @param sheetIndex ?
 * @throws InvalidFormatException 
 * @throws IOException 
 */
public ImportExcelme(MultipartFile multipartFile, int headerNum, int sheetIndex)
        throws InvalidFormatException, IOException {
    this(multipartFile.getOriginalFilename(), multipartFile.getInputStream(), headerNum, sheetIndex);
}

From source file:equipeDFK.sistemaX.controller.ControllerAgenda.java

/**
 * Mtodo que recebe uma requisio para importar os feriados,
 * ento ler o arquivo CSV e depois persistir os dados no banco
 * @param arquivoCSV//from  w w w .ja  va  2s . c  om
 * @param sobrescrever
 * @param req
 * @return String
 * @throws SQLException 
 */
@RequestMapping("openCSV")
public String OpenCSV(MultipartFile arquivoCSV, boolean sobrescrever, HttpServletRequest req)
        throws SQLException {
    GerenciadorDeFeriado gf = new GerenciadorDeFeriado();
    if (!arquivoCSV.isEmpty()) {
        try {
            byte[] b = arquivoCSV.getBytes();
            String caminho = req.getServletContext().getRealPath("/") + arquivoCSV.getOriginalFilename();
            System.out.println(caminho);
            BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(new File(caminho)));
            stream.write(b);
            stream.close();
            OpenCSV opencsv = new OpenCSV();
            if (sobrescrever) {

            } else {

            }
            gf.importaferiado(opencsv.lerCSV(new File(caminho)), sobrescrever);
            List eventos = gf.listar();
            eventos.stream().forEach((evento) -> {
                System.out.println(evento);
            });
            req.getSession().setAttribute("feriados", eventos);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
    return "managerHoliday";
}

From source file:com.web.mavenproject6.controller.DocumentUploadController.java

@ResponseBody
@RequestMapping(value = "/uploadMultipleFile", method = RequestMethod.POST)
public Object uploadMultipleFileHandler(@RequestParam("file") MultipartFile[] files) {
    System.out.print("PATH IS A:" + env.getProperty("upload.files.dir"));
    String buf = "";
    List<String> l = new ArrayList<>();
    for (MultipartFile file : files) {
        try {//from  w ww .  ja  v  a 2  s.co  m
            byte[] bytes = file.getBytes();

            String rootPath = env.getProperty("upload.files.dir");

            File dir = new File(rootPath);
            if (!dir.exists()) {
                dir.mkdirs();
                dir.setWritable(true);
            }
            File serverFile = new File(rootPath + File.separator + file.getOriginalFilename());
            serverFile.createNewFile();
            BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(serverFile));
            stream.write(bytes);
            stream.close();
            System.err.println(file.getOriginalFilename());
            buf = XLSParser.parse(env.getProperty("upload.files.dir") + "\\" + file.getOriginalFilename());

            l.add(file.getOriginalFilename());
        } catch (Exception e) {

        }
    }
    // ModelAndView model = new ModelAndView("jsp/uploadedFiles");
    //model.addObject("list", l.toArray());
    // model.addObject("buffer",buf);
    //  return model;
    return buf;
}

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

@Override
public String getJsp(ModelMap model, HttpServletRequest request, List<MultipartFile> files) {

    System.out.println("getJSP di FileBrowser");

    String baseDir = getDefaultBaseDir();
    FileBrowser fb = new FileBrowser();

    Object gotParam = model.get("gotParam");

    @SuppressWarnings("unchecked")
    Map<String, String[]> parameters = request.getParameterMap();

    for (String key : parameters.keySet()) {
        System.out.println(key); // debug
        String[] vals = parameters.get(key);
        for (String val : vals) // debug
            System.out.println(" -> " + val); // debug
        if (key.equalsIgnoreCase("d")) {
            String dirString = parameters.get(key)[0].trim();

            // prevent directory traversing
            dirString = dirString.replace("..", "");
            // clean path
            dirString = dirString.replace("/./", "/");
            dirString = dirString.replaceAll("/{2,}", "/");

            if (dirString.startsWith("/")) {
                dirString = dirString.substring(1);
            }/*from   w w  w .  ja va2s. c  o m*/

            //remove last slash

            if (dirString.lastIndexOf("/") >= 0 && dirString.lastIndexOf("/") == (dirString.length() - 1)) {
                System.out.println("stripping last slash"); // debug
                dirString = dirString.substring(0, dirString.length() - 1);
            }

            //second check
            if (dirString.lastIndexOf("/") >= 0) {
                model.addAttribute("directoryBack", dirString.substring(0, dirString.lastIndexOf("/")));
            } else {
                model.addAttribute("directoryBack", "");
            }

            dirString = dirString.concat("/");
            baseDir = baseDir + dirString;
            model.addAttribute("directory", dirString);
        }
    }

    if (gotParam != null) {
        System.out.println(gotParam); // debug
    }
    String gotAction = request.getParameter("action");
    String fileToDel = request.getParameter("toDel");
    if (gotAction != null && gotAction.equalsIgnoreCase("delete") && fileToDel != null) {
        String deleteFileString = baseDir + fileToDel;
        boolean res = deleteFile(deleteFileString);
        System.out.println("Deletted " + deleteFileString + ": " + res); // debug
    }

    model.addAttribute("operationName", this.operationName);
    model.addAttribute("operationRESTPath", this.getRESTPath());

    fb.setBaseDir(baseDir);
    fb.setRegex(null);
    fb.setScanDiretories(canNavigate);

    if (null != files && files.size() > 0) {
        List<String> fileNames = new ArrayList<String>();
        for (MultipartFile multipartFile : files) {

            String fileName = multipartFile.getOriginalFilename();
            if (!"".equalsIgnoreCase(fileName)) {
                try {
                    multipartFile.transferTo(new File(baseDir + fileName));
                } catch (IllegalStateException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                fileNames.add(fileName);
            }
            System.out.println(fileName);
        }
    }

    model.addAttribute("fileBrowser", fb);

    model.addAttribute("operations", getAvailableOperations());

    model.addAttribute("canDelete", this.canDelete);
    model.addAttribute("canUpload", this.canUpload);

    model.addAttribute("containerId", uniqueKey.toString().substring(0, 8));
    model.addAttribute("formId", uniqueKey.toString().substring(27, 36));

    return operationJSP;
}

From source file:fr.hoteia.qalingo.web.mvc.controller.catalog.AssetController.java

@RequestMapping(value = "/asset-form.html*", method = RequestMethod.POST)
public ModelAndView assetEdit(final HttpServletRequest request, final HttpServletResponse response,
        @Valid AssetForm assetForm, BindingResult result, ModelMap modelMap) throws Exception {

    if (result.hasErrors()) {
        return display(request, response, modelMap);
    }//  w  ww  .  j a va2s . co m

    final String currentAssetId = assetForm.getId();
    final Asset asset = productMarketingService.getProductMarketingAssetById(currentAssetId);
    final String currentAssetCode = asset.getCode();

    MultipartFile multipartFile = assetForm.getFile();
    if (multipartFile != null) {
        long size = multipartFile.getSize();
        asset.setFileSize(size);
    }

    try {
        if (multipartFile.getSize() > 0) {
            String pathProductMarketingImage = multipartFile.getOriginalFilename();
            String assetFileRootPath = engineSettingService.getAssetFileRootPath().getDefaultValue();
            assetFileRootPath.replaceAll("\\\\", "/");
            if (assetFileRootPath.endsWith("/")) {
                assetFileRootPath = assetFileRootPath.substring(0, assetFileRootPath.length() - 1);
            }
            String assetProductMarketingFilePath = engineSettingService.getAssetProductMarketingFilePath()
                    .getDefaultValue();
            assetProductMarketingFilePath.replaceAll("\\\\", "/");
            if (assetProductMarketingFilePath.endsWith("/")) {
                assetProductMarketingFilePath = assetProductMarketingFilePath.substring(0,
                        assetProductMarketingFilePath.length() - 1);
            }
            if (!assetProductMarketingFilePath.startsWith("/")) {
                assetProductMarketingFilePath = "/" + assetProductMarketingFilePath;
            }

            String absoluteFilePath = assetFileRootPath + assetProductMarketingFilePath + "/"
                    + asset.getType().getPropertyKey().toLowerCase() + "/" + pathProductMarketingImage;

            InputStream inputStream = multipartFile.getInputStream();
            URI url = new URI(absoluteFilePath);
            File fileAsset;
            try {
                fileAsset = new File(url);
            } catch (IllegalArgumentException e) {
                fileAsset = new File(url.getPath());
            }
            OutputStream outputStream = new FileOutputStream(fileAsset);
            int readBytes = 0;
            byte[] buffer = new byte[8192];
            while ((readBytes = inputStream.read(buffer, 0, 8192)) != -1) {
                outputStream.write(buffer, 0, readBytes);
            }
            outputStream.close();
            inputStream.close();
            asset.setPath(pathProductMarketingImage);
        }

        // UPDATE ASSET
        webBackofficeService.updateProductMarketingAsset(asset, assetForm);

    } catch (Exception e) {
        LOG.error("Can't save/update asset file!", e);
    }

    final String urlRedirect = backofficeUrlService.buildAssetDetailsUrl(currentAssetCode);
    return new ModelAndView(new RedirectView(urlRedirect));
}

From source file:cherry.foundation.async.AsyncFileProcessHandlerImplTest.java

@Test
public void testLaunchFileProcess_IOException() throws Exception {

    AsyncFileProcessHandlerImpl impl = createImpl();

    LocalDateTime now = LocalDateTime.now();
    when(bizDateTime.now()).thenReturn(now);
    when(asyncProcessStore.createFileProcess("a", now, "b", "c", "d", "e", 100L, "f")).thenReturn(10L);

    IOException ioException = new IOException();
    MultipartFile file = mock(MultipartFile.class);
    when(file.getName()).thenReturn("c");
    when(file.getOriginalFilename()).thenReturn("d");
    when(file.getContentType()).thenReturn("e");
    when(file.getSize()).thenReturn(100L);
    when(file.getInputStream()).thenThrow(ioException);

    try {/*from  ww  w  .  j a va2 s.  co  m*/
        impl.launchFileProcess("a", "b", file, "f");
        fail("Exception must be thrown");
    } catch (IllegalStateException ex) {
        assertEquals(ioException, ex.getCause());
    }
}

From source file:com.orangeandbronze.jblubble.sample.PersonController.java

protected BlobKey createPhotoBlob(MultipartFile photoFile) {
    BlobKey blobKey = null;/*from www  .j  a  va 2  s . c  o m*/
    if (photoFile.isEmpty()) {
        blobKey = null;
    } else {
        try {
            InputStream inputStream = photoFile.getInputStream();
            try {
                blobKey = blobstoreService.createBlob(inputStream, photoFile.getOriginalFilename(),
                        photoFile.getContentType());
            } finally {
                inputStream.close();
            }
        } catch (Exception e) {
            logger.error("Error saving person's photo", e);
        }
    }
    return blobKey;
}