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

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

Introduction

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

Prototype

default void transferTo(Path dest) throws IOException, IllegalStateException 

Source Link

Document

Transfer the received file to the given destination file.

Usage

From source file:net.groupbuy.service.impl.ProductImageServiceImpl.java

public void build(ProductImage productImage) {
    MultipartFile multipartFile = productImage.getFile();
    if (multipartFile != null && !multipartFile.isEmpty()) {
        try {//from w  ww  .  j a  v a 2  s . co m
            Setting setting = SettingUtils.get();
            Map<String, Object> model = new HashMap<String, Object>();
            model.put("uuid", UUID.randomUUID().toString());
            String uploadPath = FreemarkerUtils.process(setting.getImageUploadPath(), model);
            String uuid = UUID.randomUUID().toString();
            String sourcePath = uploadPath + uuid + "-source."
                    + FilenameUtils.getExtension(multipartFile.getOriginalFilename());
            String largePath = uploadPath + uuid + "-large." + DEST_EXTENSION;
            String mediumPath = uploadPath + uuid + "-medium." + DEST_EXTENSION;
            String thumbnailPath = uploadPath + uuid + "-thumbnail." + DEST_EXTENSION;

            Collections.sort(storagePlugins);
            for (StoragePlugin storagePlugin : storagePlugins) {
                if (storagePlugin.getIsEnabled()) {
                    File tempFile = new File(
                            System.getProperty("java.io.tmpdir") + "/upload_" + UUID.randomUUID() + ".tmp");
                    if (!tempFile.getParentFile().exists()) {
                        tempFile.getParentFile().mkdirs();
                    }
                    multipartFile.transferTo(tempFile);
                    addTask(sourcePath, largePath, mediumPath, thumbnailPath, tempFile,
                            multipartFile.getContentType());
                    productImage.setSource(storagePlugin.getUrl(sourcePath));
                    productImage.setLarge(storagePlugin.getUrl(largePath));
                    productImage.setMedium(storagePlugin.getUrl(mediumPath));
                    productImage.setThumbnail(storagePlugin.getUrl(thumbnailPath));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

From source file:net.groupbuy.service.impl.FileServiceImpl.java

public String upload(FileType fileType, MultipartFile multipartFile, boolean async) {
    if (multipartFile == null) {
        return null;
    }//from   www .  j  a  v a 2 s . c om
    Setting setting = SettingUtils.get();
    String uploadPath;
    if (fileType == FileType.flash) {
        uploadPath = setting.getFlashUploadPath();
    } else if (fileType == FileType.media) {
        uploadPath = setting.getMediaUploadPath();
    } else if (fileType == FileType.file) {
        uploadPath = setting.getFileUploadPath();
    } else {
        uploadPath = setting.getImageUploadPath();
    }
    try {
        Map<String, Object> model = new HashMap<String, Object>();
        model.put("uuid", UUID.randomUUID().toString());
        String path = FreemarkerUtils.process(uploadPath, model);
        String destPath = path + UUID.randomUUID() + "."
                + FilenameUtils.getExtension(multipartFile.getOriginalFilename());

        for (StoragePlugin storagePlugin : pluginService.getStoragePlugins(true)) {
            File tempFile = new File(
                    System.getProperty("java.io.tmpdir") + "/upload_" + UUID.randomUUID() + ".tmp");
            if (!tempFile.getParentFile().exists()) {
                tempFile.getParentFile().mkdirs();
            }
            multipartFile.transferTo(tempFile);
            if (async) {
                addTask(storagePlugin, destPath, tempFile, multipartFile.getContentType());
            } else {
                try {
                    storagePlugin.upload(destPath, tempFile, multipartFile.getContentType());
                } finally {
                    FileUtils.deleteQuietly(tempFile);
                }
            }
            return storagePlugin.getUrl(destPath);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

From source file:cn.org.once.cstack.service.impl.FileServiceImpl.java

/**
 * File Explorer feature/* ww w.j  a va2 s.  c  om*/
 * <p>
 * Send a file into a container
 *
 * @param containerId
 * @Param destination
 * @throws ServiceException
 */
@Override
public void sendFileToContainer(String containerId, String destination, MultipartFile fileUpload,
        String contentFileName, String contentFileData) throws ServiceException, CheckException {
    try {
        File file = null;
        File createTempHomeDirPerUsage = null;
        File homeDirectory = null;
        try {
            homeDirectory = org.apache.commons.io.FileUtils.getUserDirectory();
            createTempHomeDirPerUsage = new File(
                    homeDirectory.getAbsolutePath() + "/tmp" + System.currentTimeMillis());
            if (createTempHomeDirPerUsage.mkdirs()) {
                String fileName = null;
                // usecase : upload a file
                if (fileUpload != null) {
                    if (contentFileName == null) {
                        fileName = fileUpload.getOriginalFilename();
                        fileName = AlphaNumericsCharactersCheckUtils.deAccent(fileName);
                        fileName = fileName.replace(" ", "_");
                    } else {
                        fileName = contentFileName;
                    }
                    file = new File(createTempHomeDirPerUsage.getAbsolutePath() + "/" + fileName);
                    fileUpload.transferTo(file);
                }
                // usecase : save the content file
                else {
                    fileName = contentFileName;
                    file = new File(createTempHomeDirPerUsage.getAbsolutePath() + "/" + contentFileName);
                    FileUtils.write(file, contentFileData);
                }
                dockerService.sendFileToContainer(containerId, file.getParent(), fileName, destination);
            } else {
                throw new ServiceException("Cannot create : " + createTempHomeDirPerUsage.getAbsolutePath());
            }
        } finally {
            if (createTempHomeDirPerUsage != null) {
                boolean deleted = file.delete();
                logger.debug(file.getAbsolutePath() + " is deleted ? " + deleted);
                deleted = createTempHomeDirPerUsage.delete();
                logger.debug(createTempHomeDirPerUsage.getAbsolutePath() + " is deleted ? " + deleted);
            }
        }
        if (destination.contains("/opt/cloudunit")) {
            dockerService.execCommand(containerId, RemoteExecAction.CHANGE_CU_RIGHTS.getCommand(), true);
        }
    } catch (FatalDockerJSONException | IOException e) {
        StringBuilder msgError = new StringBuilder(512);
        msgError.append(",").append("containerId=").append(containerId);
        msgError.append(",").append("fileUpload=").append(fileUpload);
        msgError.append(",").append("destFile=").append(destination);
        throw new ServiceException("error in send file into the container : " + msgError, e);
    }

}

From source file:com.baidu.upload.controller.ImageController.java

@RequestMapping(value = "/upload", method = RequestMethod.POST)
public @ResponseBody Map<String, Object> upload(MultipartHttpServletRequest request,
        HttpServletResponse response, Integer reqid) {
    log.debug("uploadPost called");
    System.out.println("id" + reqid);
    //????//  w  w  w .  ja va  2 s  .co m
    Iterator<String> itr = request.getFileNames();
    MultipartFile mpf;
    List<Image> list = new LinkedList<Image>();

    InputStream is = null;
    List<File> newfiles = new ArrayList<File>();
    while (itr.hasNext()) {
        mpf = request.getFile(itr.next());
        //?uuid??
        String newFilenameBase = UUID.randomUUID().toString();
        //????
        String originalFileExtension = mpf.getOriginalFilename()
                .substring(mpf.getOriginalFilename().lastIndexOf("."));
        //???
        String newFilename = newFilenameBase + originalFileExtension;
        //?
        //String storageDirectory = request.getSession().getServletContext().getRealPath("/")+"pic";
        //fileUploadDirectory = storageDirectory;
        String storageDirectory = fileUploadDirectory;
        String contentType = mpf.getContentType();
        //
        File newFile = new File(storageDirectory + "/" + newFilename);
        try {
            //??       
            is = mpf.getInputStream();
            byte[] bytes = FileCopyUtils.copyToByteArray(is);
            //
            mpf.transferTo(newFile);
            //
            BufferedImage thumbnail = Scalr.resize(ImageIO.read(newFile), 290);
            //??uuid-thumbnail.png
            String thumbnailFilename = newFilenameBase + "-thumbnail.png";
            //
            File thumbnailFile = new File(storageDirectory + "/" + thumbnailFilename);
            ImageIO.write(thumbnail, "png", thumbnailFile);
            //image
            Image image = new Image();
            //?blob
            image.setImgblob(bytes);
            //image.setName(mpf.getOriginalFilename());
            image.setName(newFilename);
            image.setThumbnailFilename(thumbnailFilename);
            image.setNewFilename(newFilename);
            image.setContentType(contentType);
            image.setSize(mpf.getSize());
            image.setThumbnailSize(thumbnailFile.length());
            //?id
            int id = this.imageService.findId();
            image.setId(id);
            //url
            image.setUrl("../img/picture/" + image.getId() + ".do");
            image.setThumbnailUrl("../img/thumbnail/" + image.getId() + ".do");
            image.setDeleteUrl("../img/delete/" + image.getId() + ".do");
            image.setDeleteType("DELETE");
            //?
            image.setReqid(reqid);
            image = imageService.create(image);

            newfiles.add(newFile);
            //??
            list.add(image);

        } catch (IOException e) {
            log.error("Could not upload file " + mpf.getOriginalFilename(), e);
        } finally {
            IOUtils.closeQuietly(is);
        }

    }

    Map<String, Object> files = new HashMap<String, Object>();
    files.put("files", list);
    return files;
}

From source file:de.zib.gndms.dspace.service.SliceServiceImpl.java

@Override
@RequestMapping(value = "/_{subspaceId}/_{sliceKindId}/_{sliceId}/_{fileName:.*}", method = RequestMethod.POST)
@Secured("ROLE_USER")
public ResponseEntity<Integer> setFileContent(@PathVariable final String subspaceId,
        @PathVariable final String sliceKindId, @PathVariable final String sliceId,
        @PathVariable final String fileName, @RequestParam("file") final MultipartFile file,
        @RequestHeader("DN") final String dn) {
    GNDMSResponseHeader headers = setHeaders(subspaceId, sliceKindId, sliceId, dn);

    try {//from  w  ww .j a v a  2  s  . co  m
        Subspace space = subspaceProvider.get(subspaceId);
        Slice slice = findSliceOfKind(subspaceId, sliceKindId, sliceId);
        String path = space.getPathForSlice(slice);
        File newFile = new File(path + File.separatorChar + fileName);

        if (newFile.exists()) {
            logger.warn("File " + newFile + "will be overwritten. ");
        }

        final long sliceMaxSize = slice.getTotalStorageSize();
        long sliceSize = sliceProvider.getDiskUsage(subspaceId, sliceId);
        if (sliceSize >= sliceMaxSize)
            throw new IOException(
                    "Slice " + sliceId + " has reached maximum size of " + sliceMaxSize + " Bytes");

        file.transferTo(newFile);

        //DataOutputStream dos = new DataOutputStream(new FileOutputStream(newFile));

        //dos.write(file.getBytes());
        //dos.close();
        return new ResponseEntity<Integer>(0, headers, HttpStatus.OK);
    } catch (NoSuchElementException ne) {
        logger.warn(ne.getMessage(), ne);
        return new ResponseEntity<Integer>(0, headers, HttpStatus.NOT_FOUND);
    } catch (FileNotFoundException e) {
        logger.warn(e.getMessage(), e);
        return new ResponseEntity<Integer>(0, headers, HttpStatus.FORBIDDEN);
    } catch (IOException e) {
        logger.warn(e.getMessage(), e);
        return new ResponseEntity<Integer>(0, headers, HttpStatus.FORBIDDEN);
    }
}

From source file:com.zb.app.biz.service.impl.FileServiceImpl.java

public Result createFilePath(MultipartFile file, Long... id) {
    // ?/*from  w  w w. j a va  2s. c o  m*/
    if (file == null) {
        return Result.failed();
    }
    if (!file.isEmpty()) {
        if (StringUtils.isEmpty(file.getOriginalFilename())) {
            return Result.failed();
        }
        // int lastIndex = StringUtils.lastIndexOf(file.getOriginalFilename(), ".");
        // String suffix = StringUtils.substring(file.getOriginalFilename(), lastIndex);
        String[] suffixArray = StringUtils.split(file.getOriginalFilename(), ".");
        if (Argument.isEmptyArray(suffixArray)) {
            return Result.failed();
        }
        String prefix = null;
        if (Argument.isEmptyArray(id)) {
            prefix = SerialNumGenerator.createSerNo(null, SerialNumGenerator.p_prefix);
        } else {
            prefix = SerialNumGenerator.createSerNo(id[0], SerialNumGenerator.p_prefix);
        }
        String suffix = null;
        if (suffixArray.length == 1) {
            suffix = "jpg";
        } else {
            suffix = suffixArray[suffixArray.length - 1];
        }
        String filePath = prefix + DELIMITER + suffix;
        try {
            // 
            file.transferTo(new File(UPLOAD_TMP_PATH + filePath));
            return Result.success(null, STATIC_TMP_IMG + filePath);
        } catch (Exception e) {
            logger.error(e.getMessage());
            return Result.failed();
        }
    }
    return Result.failed();
}

From source file:org.openmrs.module.dhisconnector.api.impl.DHISConnectorServiceImpl.java

@Override
public String uploadDHIS2APIBackup(MultipartFile dhis2APIBackup) {
    String msg = "";
    String outputFolder = OpenmrsUtil.getApplicationDataDirectory() + DHISCONNECTOR_TEMP_FOLDER;
    File temp = new File(outputFolder);
    File dhis2APIBackupRootDir = new File(
            OpenmrsUtil.getApplicationDataDirectory() + DHISCONNECTOR_DHIS2BACKUP_FOLDER);

    if (!temp.exists()) {
        temp.mkdirs();//from   w  w w  .j ava 2 s.c  o m
    }

    File dest = new File(outputFolder + File.separator + dhis2APIBackup.getOriginalFilename());

    if (!dhis2APIBackup.isEmpty() && dhis2APIBackup.getOriginalFilename().endsWith(".zip")) {
        try {
            dhis2APIBackup.transferTo(dest);

            if (dest.exists() && dest.isFile()) {
                File unzippedAt = new File(outputFolder + File.separator + "api");
                File api = new File(dhis2APIBackupRootDir.getPath() + File.separator + "api");

                unZipDHIS2APIBackupToTemp(dest.getCanonicalPath());
                if ((new File(outputFolder)).list().length > 0 && unzippedAt.exists()) {
                    if (!dhis2APIBackupRootDir.exists()) {
                        dhis2APIBackupRootDir.mkdirs();
                    }

                    if (FileUtils.sizeOfDirectory(dhis2APIBackupRootDir) > 0 && unzippedAt.exists()
                            && unzippedAt.isDirectory()) {
                        if (checkIfDirContainsFile(dhis2APIBackupRootDir, "api")) {

                            FileUtils.deleteDirectory(api);
                            api.mkdir();
                            msg = Context.getMessageSourceService()
                                    .getMessage("dhisconnector.dhis2backup.replaceSuccess");
                        } else {
                            msg = Context.getMessageSourceService()
                                    .getMessage("dhisconnector.dhis2backup.import.success");
                        }
                        FileUtils.copyDirectory(unzippedAt, api);
                        FileUtils.deleteDirectory(temp);
                    }
                }
            }
        } catch (IllegalStateException e) {
            msg = Context.getMessageSourceService().getMessage("dhisconnector.dhis2backup.failure");
            e.printStackTrace();
        } catch (IOException e) {
            msg = Context.getMessageSourceService().getMessage("dhisconnector.dhis2backup.failure");
            e.printStackTrace();
        }
    } else {
        msg = Context.getMessageSourceService().getMessage("dhisconnector.dhis2backup.failure");
    }

    return msg;
}

From source file:com.fengduo.bee.service.impl.file.FileServiceImpl.java

public Result createFilePath(MultipartFile file, IFileCreate... ihandle) {
    // ?//  ww w  .ja v a 2 s . c  o  m
    if (file == null) {
        return Result.failed();
    }
    if (!file.isEmpty()) {
        if (StringUtils.isEmpty(file.getOriginalFilename())) {
            return Result.failed();
        }
        String[] suffixArray = StringUtils.split(file.getOriginalFilename(), DELIMITER);
        if (Argument.isEmptyArray(suffixArray)) {
            return Result.failed();
        }
        String prefix = null;
        if (Argument.isEmptyArray(ihandle)) {
            prefix = Identities.uuid2();
        } else {
            prefix = ihandle[0].build(Identities.uuid2(), StringUtils.EMPTY);
        }
        String suffix = null;
        if (suffixArray.length == 1) {
            suffix = "jpg";
        } else {
            suffix = suffixArray[1];
        }
        String filePath = prefix + DELIMITER + suffix;
        // String filePath48 = prefix + "=48x48" + DELIMITER + suffix;
        try {
            File targetFile = new File(UPLOAD_TMP_PATH + filePath);
            if (targetFile != null && targetFile.getParentFile() != null
                    && !targetFile.getParentFile().exists()) {
                logger.error("?,!");
                targetFile.getParentFile().mkdirs();
            }
            // 
            file.transferTo(new File(UPLOAD_TMP_PATH + filePath));
            // FileUtils.copyFile(new File(UPLOAD_TMP_PATH + filePath), new
            // File(UPLOAD_TMP_PATH + filePath48));
            return Result.success(null, STATIC_TMP_IMG + filePath);
        } catch (Exception e) {
            logger.error(":" + e.getMessage());
            return Result.failed(":" + e.getMessage());
        }
    }
    return Result.failed();
}

From source file:com.pkrete.locationservice.admin.service.illustrations.MapsServiceImpl.java

/**
 * Saves the given file in the maps directory of the Admin app under the
 * given language./*from w  w  w .  java2  s  . co  m*/
 *
 * @param file file to be saved
 * @param language language of the file
 * @param owner owner of the file
 * @return name of the file if and only if the file was saved; otherwise
 * null
 */
@Override
public String upload(MultipartFile file, Language language, Owner owner) {
    // Check for null values
    if (file == null || owner == null || language == null) {
        logger.warn("Writing map file to disk failed! File or owner can not be null.");
        return null;
    }

    // Get path of the maps admin dir
    String path = Settings.getInstance().getMapsPathAdmin(owner.getCode());
    // Add language code to the path
    path += language.getCode() + "/";
    // Get the name of the file
    String name = file.getOriginalFilename();
    // Name must be unique inside the target directory, NOT between
    // all the language directories
    name = this.getUniqueName(path, name);
    // Absolute target path
    path += name;

    // Create a new File object for the uploaded file
    File mapFile = new File(path);
    logger.info("Write uploaded map file to disk. Path : \"{}\"", path);

    try {
        // Write the uploaded file to disk
        file.transferTo(mapFile);
    } catch (IOException ex) {
        logger.warn("Writing map file to disk failed!");
        logger.error(ex.getMessage(), ex);
        return null;
    }
    // Check that the file really exists
    if (!fileService.exists(path)) {
        logger.warn("Writing map file to disk failed! File doesn't exist. Path : \"{}\"", path);
        return null;
    }
    logger.info("Writing uploaded map file to disk done. Path : \"{}\"", path);
    return name;
}

From source file:org.openmrs.module.dhisconnector.api.impl.DHISConnectorServiceImpl.java

@SuppressWarnings("rawtypes")
@Override/* w  ww.  ja v  a2s .com*/
public String uploadMappings(MultipartFile mapping) {
    String msg = "";
    String tempFolderName = OpenmrsUtil.getApplicationDataDirectory() + DHISCONNECTOR_TEMP_FOLDER
            + File.separator;
    String mappingFolderName = OpenmrsUtil.getApplicationDataDirectory() + DHISCONNECTOR_MAPPINGS_FOLDER
            + File.separator;
    String mappingName = mapping.getOriginalFilename();

    if (mappingName.endsWith(".zip")) {
        boolean allFailed = true;
        File tempMappings = new File(tempFolderName + mappingName);

        (new File(tempFolderName)).mkdirs();
        try {
            mapping.transferTo(tempMappings);

            try {
                ZipFile zipfile = new ZipFile(tempMappings);

                for (Enumeration e = zipfile.entries(); e.hasMoreElements();) {
                    ZipEntry entry = (ZipEntry) e.nextElement();

                    if (entry.isDirectory()) {
                        System.out.println("Incorrect file (Can't be a folder instead): " + entry.getName()
                                + " has been ignored");
                    } else if (entry.getName().endsWith(DHISCONNECTOR_MAPPING_FILE_SUFFIX)) {
                        File outputFile = new File(mappingFolderName, entry.getName());

                        if (outputFile.exists()) {
                            System.out.println(
                                    "File: " + outputFile.getName() + " already exists and has been ignored");
                        } else {
                            BufferedInputStream inputStream = new BufferedInputStream(
                                    zipfile.getInputStream(entry));
                            BufferedOutputStream outputStream = new BufferedOutputStream(
                                    new FileOutputStream(outputFile));

                            try {
                                System.out.println("Extracting: " + entry);
                                IOUtils.copy(inputStream, outputStream);
                                allFailed = false;
                            } finally {
                                outputStream.close();
                                inputStream.close();
                            }
                        }
                    } else {
                        System.out.println("Incorrect file: " + entry.getName() + " has been ignored");
                    }
                }
                if (!allFailed) {
                    msg = Context.getMessageSourceService()
                            .getMessage("dhisconnector.uploadMapping.groupSuccess");
                } else {
                    msg = Context.getMessageSourceService().getMessage("dhisconnector.uploadMapping.allFailed");
                }
                FileUtils.deleteDirectory(new File(tempFolderName));
            } catch (Exception e) {
                System.out.println("Error while extracting file:" + mapping.getName() + " ; " + e);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    } else if (mappingName.endsWith(DHISCONNECTOR_MAPPING_FILE_SUFFIX)) {
        try {
            File uploadedMapping = new File(mappingFolderName + mappingName);
            if (uploadedMapping.exists()) {
                msg = Context.getMessageSourceService().getMessage("dhisconnector.uploadMapping.exists");
            } else {
                mapping.transferTo(uploadedMapping);
                msg = Context.getMessageSourceService().getMessage("dhisconnector.uploadMapping.singleSuccess");
            }

        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    } else {
        msg = Context.getMessageSourceService().getMessage("dhisconnector.uploadMapping.wrongType");
    }

    return msg;
}