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.ProtectServiceImpl.java

@Override
public DownloadForm protect(final MultipartFile file, final String password, final String repeatedPassword,
        final HttpServletResponse response)
        throws COSVisitorException, IOException, BadSecurityHandlerException {

    DownloadForm result = new DownloadForm();

    if (!file.isEmpty() && StringUtils.isNotBlank(password) && StringUtils.isNotBlank(repeatedPassword)
            && password.equals(repeatedPassword)) {

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

        try {/*www .j  a v  a2 s  .c om*/
            // File is protected
            this.pdfGal.protect(inputUri, outputUri, password);
        } catch (COSVisitorException | IOException | BadSecurityHandlerException 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:de.iteratec.iteraplan.presentation.dialog.ExcelImport.ExcelImportController.java

/**
 * Tests if the given <code>file</code> is an excel file in version 2003 or 2007.
 * //from  w w w.  ja v  a 2s.  c  o  m
 * @param file
 *          the file to be tested
 * @return <code>true</code> if <code>file</code> is an excel file, <code>false</code> if
 *         <code>file</code> is <code>null</code> or has wrong type.
 */
private boolean checkFile(MultipartFile file) {
    if (file == null) {
        return false;
    }
    // checks for Office Version 2003; Office 2007 format is not yet supported
    if (file.getOriginalFilename().endsWith(".xls")) {
        return true;
    }
    return false;
}

From source file:de.iteratec.iteraplan.presentation.dialog.ExcelImport.ImportFrontendServiceImpl.java

private void setFileContentToMemBean(MassdataMemBean memBean, MultipartFile file) {
    try {//from  w  w w  .  ja  v  a2 s  .com
        memBean.setFileContent(file.getBytes());
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("File length: {0}", Integer.valueOf(file.getBytes().length));
        }
    } catch (IOException e) {
        LOGGER.error("Error reading file \"{0}\"", file.getOriginalFilename());
        throw new IteraplanTechnicalException(IteraplanErrorMessages.GENERAL_TECHNICAL_ERROR, e);
    }
}

From source file:eionet.transfer.dao.UploadsServiceDBFiles.java

public void storeFile(MultipartFile myFile, String uuidName, int fileTTL) throws IOException {
    storageService.save(myFile, uuidName);
    System.out.println("After storage save");
    long now = System.currentTimeMillis();
    Date expirationDate = new Date(now + fileTTL * 3600L * 24L * 1000L);

    Upload rec = new Upload();
    rec.setId(uuidName);/*from   w w  w  . ja  va2s  .c  o m*/
    rec.setFilename(Filenames.removePath(myFile.getOriginalFilename()));
    rec.setContentType(myFile.getContentType());
    rec.setExpires(expirationDate);
    rec.setSize(myFile.getSize());
    String userName = getUserName();
    rec.setUploader(userName);
    System.out.println("Before metadata save");
    metadataService.save(rec);
    System.out.println("After metadata save");
    logger.info("Uploaded: " + myFile.getOriginalFilename() + " by " + userName);
}

From source file:pdl.web.service.common.FileService.java

public Map<String, String> uploadFile(MultipartFile theFile, String type, String username) {
    Map<String, String> rtnJson = new TreeMap<String, String>();
    try {/* www .  jav  a  2s  . co  m*/
        /*if(type.isEmpty())
        type="blob";*/

        String fileUid = null;
        if (theFile.getSize() > 0) {
            InputStream fileIn = theFile.getInputStream();
            fileUid = fileTool.createFile(type, fileIn, theFile.getOriginalFilename(), username);
        }

        if (fileUid == null)
            throw new Exception();

        rtnJson.put("id", fileUid);
    } catch (Exception ex) {
        rtnJson.put("error", "File upload failed for " + theFile.getOriginalFilename());
        rtnJson.put("message", ex.toString());
    }

    return rtnJson;
}

From source file:ca.intelliware.ihtsdo.mlds.web.rest.MemberResource.java

private File updateFile(MultipartFile multipartFile, File existingFile) throws IOException {
    File newFile = new File();

    if (existingFile != null) {
        entityManager.detach(existingFile);
    }//  w  w w .ja  va 2  s  . c  o m

    Blob blob = blobHelper.createBlobFrom(multipartFile);
    newFile.setContent(blob);
    newFile.setCreator(sessionService.getUsernameOrNull());
    newFile.setFilename(multipartFile.getOriginalFilename());
    newFile.setMimetype(multipartFile.getContentType());
    newFile.setLastUpdated(Instant.now());

    fileRepository.save(newFile);
    return newFile;
}

From source file:com.aboutdata.web.controller.member.SettingsController.java

/**
 * @1 ?//w w  w  .  ja  v a 2s  .co  m
 * @2 ??40x40 60x60 200x200
 * @3 Avatar ???? ??ids(?)?
 * @param multipartFile
 * @param model
 * @return
 */
@RequestMapping(value = "/avatar", method = RequestMethod.POST)
public String updateAvatar(MultipartFile multipartFile, ModelMap model) {
    if (!multipartFile.isEmpty()) {
        Member member = memberService.getCurrent();
        //?????
        imageGraphicsService.buildAvatar(member.getId(), multipartFile);

        String type = multipartFile.getContentType().split("/")[1];
        member.setAvatar(multipartFile.getOriginalFilename());
        member.setAvatarType(type);
        memberService.update(member);
    }
    return "redirect:/member/settings/avatar";
}

From source file:de.whs.poodle.repositories.FileRepository.java

public int uploadFile(MultipartFile file) throws IOException {
    InputStream in = file.getInputStream();

    KeyHolder keyHolder = new GeneratedKeyHolder();
    jdbc.update(con -> {/*  w w  w .  j av  a 2  s  . c  o m*/
        PreparedStatement ps = con.prepareStatement(
                "INSERT INTO uploaded_file(data,mimetype,filename) VALUES(?,?,?)", new String[] { "id" });

        ps.setBinaryStream(1, in, file.getSize());
        ps.setString(2, file.getContentType());
        ps.setString(3, file.getOriginalFilename());
        return ps;
    }, keyHolder);

    return keyHolder.getKey().intValue();
}

From source file:com.codestudio.dorm.web.support.spring.upload.FileUploadSupport.java

/**
 * //from  w w w . j  ava 2s  .c om
 * 
 * @param file
 * @param type
 * @return
 */
public Attachment upload(long userId, MultipartFile file, String type) {
    if (StringUtils.isBlank(type)) {
        type = DEFAULT_TYPE;
    }
    FileOutputStream fs = null;
    InputStream is = null;
    if (file == null) {
        return null;
    }
    try {
        is = file.getInputStream();
        String orgFileName = file.getOriginalFilename();
        int i = orgFileName.lastIndexOf('.');
        String ext = "";
        if (i > 0) {
            ext = orgFileName.substring(i);
        }
        Date now = new Date();
        String filePath = "/" + type + "/"
                + DateUtils.dateConvert2String(now, DateUtils.DATEPATTERN_YYYY_MM_DD4FILE) + "/";

        String fileName = now.getTime() + "" + ((int) (Math.random() * 10));

        File f = new File(uploadFilePath + filePath);
        if (!f.exists()) {
            f.mkdirs();
        }
        fs = new FileOutputStream(uploadFilePath + filePath + fileName + ext);
        byte[] buffer = new byte[1024 * 1024];
        int byteread = 0;
        while ((byteread = is.read(buffer)) != -1) {
            fs.write(buffer, 0, byteread);
            fs.flush();
        }

        // ???
        Attachment attachment = new Attachment();
        attachment.setSrcName(file.getOriginalFilename());
        attachment.setDescName(fileName);
        attachment.setFileType(type);
        attachment.setExt(ext);
        attachment.setPath(filePath);
        attachment.setSize(file.getSize());
        attachment.setUserId(userId);
        attachmentService.add(attachment);
        return attachment;
    } catch (Exception e) {
        logger.error("upload file error:", e);
    } finally {
        try {
            fs.close();
            is.close();
        } catch (Exception e) {
            logger.error("close file error:", e);
        }
    }
    return null;
}

From source file:fr.mby.opa.pics.web.controller.UploadPicturesController.java

/***************************************************
 * URL: /upload/jqueryUpload upload(): receives files
 * //from www  .  ja v  a 2  s.com
 * @param request
 *            : MultipartHttpServletRequest auto passed
 * @param response
 *            : HttpServletResponse auto passed
 * @return LinkedList<FileMeta> as json format
 ****************************************************/
@ResponseBody
@RequestMapping(value = "/jqueryUpload", method = RequestMethod.POST)
public FileMetaList jqueryUpload(@RequestParam final Long albumId, final MultipartHttpServletRequest request,
        final HttpServletResponse response) throws Exception {
    Assert.notNull(albumId, "No Album Id supplied !");

    final FileMetaList files = new FileMetaList();

    // 1. build an iterator
    final Iterator<String> itr = request.getFileNames();

    // 2. get each file
    while (itr.hasNext()) {

        // 2.1 get next MultipartFile
        final MultipartFile mpf = request.getFile(itr.next());

        // Here the file is uploaded

        final String originalFilename = mpf.getOriginalFilename();
        final String contentType = mpf.getContentType();

        final Matcher zipMatcher = UploadPicturesController.ZIP_CONTENT_TYPE_PATTERN.matcher(contentType);
        if (zipMatcher.find()) {

            // 2.3 create new fileMeta
            final FileMeta zipMeta = new FileMeta();
            zipMeta.setFileName(originalFilename);
            zipMeta.setFileSize(mpf.getSize() / 1024 + " Kb");
            zipMeta.setFileType(mpf.getContentType());

            final List<Path> picturesPaths = this.processArchive(mpf);

            final Collection<Future<Void>> futures = new ArrayList<>(picturesPaths.size());
            final ExecutorService executorService = Executors
                    .newFixedThreadPool(Runtime.getRuntime().availableProcessors());

            for (final Path picturePath : picturesPaths) {
                final Future<Void> future = executorService.submit(new Callable<Void>() {

                    @Override
                    public Void call() throws Exception {
                        final String pictureFileName = picturePath.getName(picturePath.getNameCount() - 1)
                                .toString();
                        final byte[] pictureContents = Files.readAllBytes(picturePath);

                        final FileMeta pictureMeta = new FileMeta();
                        try {
                            final Picture picture = UploadPicturesController.this.createPicture(albumId,
                                    pictureFileName.toString(), pictureContents);
                            final Long imageId = picture.getImage().getId();
                            final Long thumbnailId = picture.getThumbnail().getId();

                            pictureMeta.setFileName(pictureFileName);
                            pictureMeta.setFileSize(pictureContents.length / 1024 + " Kb");
                            pictureMeta.setFileType(Files.probeContentType(picturePath));
                            pictureMeta.setUrl(
                                    response.encodeURL(ImageController.IMAGE_CONTROLLER_PATH + "/" + imageId));
                            pictureMeta.setThumbnailUrl(response
                                    .encodeURL(ImageController.IMAGE_CONTROLLER_PATH + "/" + thumbnailId));
                        } catch (final PictureAlreadyExistsException e) {
                            // Picture already exists !
                            pictureMeta.setError(
                                    UploadPicturesController.PICTURE_ALREADY_EXISTS_MSG + e.getFilename());
                        } catch (final UnsupportedPictureTypeException e) {
                            // Picture already exists !
                            pictureMeta.setError(
                                    UploadPicturesController.UNSUPPORTED_PICTURE_TYPE_MSG + e.getFilename());
                        }

                        files.add(pictureMeta);

                        return null;
                    }
                });
                futures.add(future);
            }

            for (final Future<Void> future : futures) {
                future.get();
            }

            files.add(zipMeta);
        }

        final Matcher imgMatcher = UploadPicturesController.IMG_CONTENT_TYPE_PATTERN.matcher(contentType);
        if (imgMatcher.find()) {
            // 2.3 create new fileMeta
            final FileMeta fileMeta = new FileMeta();
            try {
                final byte[] fileContents = mpf.getBytes();
                final Picture picture = this.createPicture(albumId, originalFilename, fileContents);

                final Long imageId = picture.getImage().getId();
                final Long thumbnailId = picture.getThumbnail().getId();

                fileMeta.setFileName(originalFilename);
                fileMeta.setFileSize(mpf.getSize() / 1024 + " Kb");
                fileMeta.setFileType(mpf.getContentType());
                fileMeta.setBytes(fileContents);
                fileMeta.setUrl(response.encodeURL(ImageController.IMAGE_CONTROLLER_PATH + "/" + imageId));
                fileMeta.setThumbnailUrl(
                        response.encodeURL(ImageController.IMAGE_CONTROLLER_PATH + "/" + thumbnailId));

                // 2.4 add to files
                files.add(fileMeta);
            } catch (final PictureAlreadyExistsException e) {
                // Picture already exists !
                fileMeta.setError(UploadPicturesController.PICTURE_ALREADY_EXISTS_MSG);
            }
        }

    }

    // result will be like this
    // {files:[{"fileName":"app_engine-85x77.png","fileSize":"8 Kb","fileType":"image/png"},...]}
    return files;
}