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:org.pdfgal.pdfgalweb.services.impl.ReindexServiceImpl.java

@Override
public DownloadForm reindex(final MultipartFile file, final List<Integer> pagesList,
        final List<NumberingStyle> numberingStylesList, final HttpServletResponse response) throws Exception {

    DownloadForm result = new DownloadForm();

    if (file != null && CollectionUtils.isNotEmpty(pagesList) && CollectionUtils.isNotEmpty(numberingStylesList)
            && response != null) {

        final String originalName = file.getOriginalFilename();
        final String inputUri = this.fileUtils.saveFile(file);
        final String outputUri = this.fileUtils.getAutogeneratedName(originalName);

        // File is reindexed
        try {//ww  w .  j  av a  2  s .com
            final List<PDFGalPageNumbering> pdfGalPageNumberingList = this
                    .createPdfGalPageNumberingList(pagesList, numberingStylesList);
            this.pdfGal.reIndexPageNumbers(inputUri, outputUri, pdfGalPageNumberingList);
        } catch (COSVisitorException | IOException e) {
            // Temporal files are deleted from system
            this.fileUtils.delete(inputUri);
            this.fileUtils.delete(outputUri);
            throw e;
        }

        // Temporal files are deleted from system
        this.fileUtils.delete(inputUri);

        result = new DownloadForm(outputUri, originalName);
    }

    return result;
}

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

@Test
public void testLaunchFileProcess_2_ARGS() 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", "g", "h"))
            .thenReturn(10L);/*from  w w  w .j a  v a  2 s  .c  o  m*/

    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()).thenReturn(new ByteArrayInputStream(new byte[0]));

    @SuppressWarnings("rawtypes")
    ArgumentCaptor<Map> message = ArgumentCaptor.forClass(Map.class);

    long asyncId = impl.launchFileProcess("a", "b", file, "f", "g", "h");
    assertEquals(10L, asyncId);
    verify(jmsOperations).convertAndSend(message.capture(), eq(messagePostProcessor));
    assertEquals("10", message.getValue().get("asyncId"));
    String fileName = (String) message.getValue().get("file");
    assertTrue(fileName.startsWith((new File(tempDir, "prefix_")).getAbsolutePath()));
    assertTrue(fileName.endsWith(".csv"));
    assertEquals("c", message.getValue().get("name"));
    assertEquals("d", message.getValue().get("originalFilename"));
    assertEquals("e", message.getValue().get("contentType"));
    assertEquals("100", message.getValue().get("size"));
    assertEquals("f", message.getValue().get("handlerName"));
    assertEquals("g", message.getValue().get("0"));
    assertEquals("h", message.getValue().get("1"));
    verify(asyncProcessStore).createFileProcess("a", now, "b", "c", "d", "e", 100L, "f", "g", "h");
    verify(asyncProcessStore).updateToLaunched(10L, now);
}

From source file:fr.olympicinsa.riocognized.AdvertController.java

@RequestMapping(value = "/save", method = RequestMethod.POST)
public String save(@ModelAttribute("image") ImagePub image, @RequestParam("file") MultipartFile file) {

    System.out.println("Name:" + image.getName());
    System.out.println("Desc:" + image.getDescription());
    System.out.println("File:" + file.getName());
    System.out.println("ContentType:" + file.getContentType());

    try {// www.  ja  v a 2s  . c o  m
        byte[] blob = IOUtils.toByteArray(file.getInputStream());

        image.setFilename(file.getOriginalFilename());
        image.setContent(blob);
        image.setContentType(file.getContentType());
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        imagePubRepository.save(image);
    } catch (Exception e) {
        e.printStackTrace();
    }

    return "redirect:/ad/manage";
}

From source file:org.opentestsystem.authoring.testauth.rest.FileGroupController.java

@ResponseStatus(HttpStatus.CREATED)
@RequestMapping(value = "/fileGroup/gridFsFile", method = RequestMethod.POST, consumes = MediaType.MULTIPART_FORM_DATA_VALUE, produces = MediaType.TEXT_PLAIN_VALUE)
@Secured({ "ROLE_Result Upload Modify" })
@ResponseBody/*ww  w  . ja  va  2  s .co  m*/
public String uploadGridFsFile(@RequestParam("gridFsFile") final MultipartFile gridFsFile,
        final HttpServletRequest request, final HttpServletResponse response) throws IOException {
    String jsonAsStringForIE = null;
    try {
        final GridFSFile savedFile = this.fileGroupService.saveGridFsFile(gridFsFile.getOriginalFilename(),
                gridFsFile.getBytes(), gridFsFile.getContentType());
        jsonAsStringForIE = savedFile.toString();
    } catch (final LocalizedException e) {
        // return a 201 here -
        // IE9 and browsers which require iframe transport must receive an OK status to get the response result after file upload
        jsonAsStringForIE = this.objectMapper.writeValueAsString(super.handleException(e));
    } catch (final IOException e) {
        // return a 201 here -
        // IE9 and browsers which require iframe transport must receive an OK status to get the response result after file upload
        jsonAsStringForIE = this.objectMapper.writeValueAsString(super.handleException(e));
    }

    return jsonAsStringForIE;
}

From source file:com.github.cherimojava.orchidae.controller.PictureController.java

/**
 * uploads multiple files into the system for the current user
 * // w  ww .  jav a  2s  . c  om
 * @param request
 *            request with pictures to store
 * @return {@link org.springframework.http.HttpStatus#CREATED} if the upload was successful or
 *         {@link org.springframework.http.HttpStatus#OK} if some of the pictures couldn't be uploaded together with
 *         information which pictures couldn't be uploaded
 * @since 1.0.0
 */
@RequestMapping(method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public ResponseEntity<String> handleFileUpload(MultipartHttpServletRequest request) {
    List<String> badFiles = Lists.newArrayList();
    User user = userUtil
            .getUser((String) SecurityContextHolder.getContext().getAuthentication().getPrincipal());
    for (Iterator<String> it = request.getFileNames(); it.hasNext();) {
        MultipartFile file = request.getFile(it.next());
        // Create uuid and Picture entity
        Picture picture = factory.create(Picture.class);
        picture.setUser(user);
        picture.setTitle(StringUtils.split(file.getOriginalFilename(), ".")[0]);
        picture.setId(generateId());
        picture.setOriginalName(file.getOriginalFilename());
        picture.setUploadDate(DateTime.now());

        String type = StringUtils.substringAfterLast(file.getOriginalFilename(), ".");

        try {
            File storedPicture = fileUtil.getFileHandle(picture.getId());
            // save picture
            file.transferTo(storedPicture);

            // read some some properties from it
            BufferedImage image = ImageIO.read(storedPicture);
            picture.setHeight(image.getHeight());
            picture.setWidth(image.getWidth());
            picture.setAccess(Access.PRIVATE);// TODO for now only private access
            createSmall(picture.getId(), image, type);
            LOG.info("Uploaded {} and assigned id {}", file.getOriginalFilename(), picture.getId());
            checkBatch(picture, request);
            picture.save();
        } catch (Exception e) {
            LOG.warn("failed to store picture", e);
            badFiles.add(file.getOriginalFilename());
        }
    }
    if (badFiles.isEmpty()) {
        return new ResponseEntity<>("You successfully uploaded!", HttpStatus.CREATED);
    } else {
        return new ResponseEntity<>(
                "Could not upload all files. Failed to upload: " + Joiner.on(",").join(badFiles),
                HttpStatus.OK);
    }
}

From source file:com.eryansky.modules.disk.service.DiskManager.java

/**
 * /*  www.j a va 2s .c o  m*/
 * @param sessionInfo
 * @param folder
 * @param uploadFile
 * @throws Exception
 */
public File fileUpload(SessionInfo sessionInfo, Folder folder, MultipartFile uploadFile) throws Exception {
    File file = null;
    /*      Exception exception = null;
    */
    java.io.File tempFile = null;
    try {
        String relativeDir = DiskUtils.getRelativePath(folder, sessionInfo.getUserId());
        String fullName = uploadFile.getOriginalFilename();
        String code = FileUploadUtils.encodingFilenamePrefix(sessionInfo.getUserId().toString(), fullName);
        String storePath = iFileManager.getStorePath(folder, sessionInfo.getUserId(),
                uploadFile.getOriginalFilename());

        String fileTemp = AppConstants.getDiskTempDir() + java.io.File.separator + code;
        tempFile = new java.io.File(fileTemp);
        FileOutputStream fos = FileUtils.openOutputStream(tempFile);
        IOUtils.copy(uploadFile.getInputStream(), fos);

        iFileManager.saveFile(storePath, fileTemp, false);
        file = new File();
        file.setFolder(folder);
        file.setCode(code);
        file.setUserId(sessionInfo.getUserId());
        file.setName(fullName);
        file.setFilePath(storePath);
        file.setFileSize(uploadFile.getSize());
        file.setFileSuffix(FilenameUtils.getExtension(fullName));
        fileManager.save(file);
    } catch (Exception e) {
        // exception = e;
        throw new ServiceException(DiskUtils.UPLOAD_FAIL_MSG + e.getMessage(), e);
    } finally {
        //         if (exception != null && file != null) {
        //            DiskUtils.deleteFile(null, file.getId());
        //         }
        if (tempFile != null && tempFile.exists()) {
            tempFile.delete();
        }

    }
    return file;

}

From source file:org.openmrs.module.owa.web.controller.OwaRestController.java

@RequestMapping(value = "/rest/owa/addapp", method = RequestMethod.POST)
@ResponseBody/*from   w  w  w  .  ja  v  a 2s . c  om*/
public List<App> upload(@RequestParam("file") MultipartFile file, HttpServletRequest request,
        HttpServletResponse response) throws IOException {
    List<App> appList = new ArrayList<>();
    if (Context.hasPrivilege("Manage OWA")) {
        String message;
        HttpSession session = request.getSession();
        if (!file.isEmpty()) {
            String fileName = file.getOriginalFilename();
            File uploadedFile = new File(file.getOriginalFilename());
            file.transferTo(uploadedFile);
            try (ZipFile zip = new ZipFile(uploadedFile)) {
                if (zip.size() == 0) {
                    message = messageSourceService.getMessage("owa.blank_zip");
                    log.warn("Zip file is empty");
                    session.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, message);
                    response.sendError(500, message);
                } else {
                    ZipEntry entry = zip.getEntry("manifest.webapp");
                    if (entry == null) {
                        message = messageSourceService.getMessage("owa.manifest_not_found");
                        log.warn("Manifest file could not be found in app");
                        uploadedFile.delete();
                        session.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, message);
                        response.sendError(500, message);
                    } else {
                        String contextPath = request.getScheme() + "://" + request.getServerName() + ":"
                                + request.getServerPort() + request.getContextPath();
                        appManager.installApp(uploadedFile, fileName, contextPath);
                        message = messageSourceService.getMessage("owa.app_installed");
                        session.setAttribute(WebConstants.OPENMRS_MSG_ATTR, message);
                    }
                }
            } catch (Exception e) {
                message = messageSourceService.getMessage("owa.not_a_zip");
                log.warn("App is not a zip archive");
                uploadedFile.delete();
                session.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, message);
                response.sendError(500, message);
            }
        }
        appManager.reloadApps();
        appList = appManager.getApps();
    }
    return appList;
}