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:com.mmj.app.biz.service.impl.FileServiceImpl.java

public Result createFilePath(MultipartFile file, String filePath) {
    if (file == null || StringUtils.isEmpty(filePath)) {
        return Result.failed();
    }//from   w ww.jav  a2s  .  c  o m
    if (!file.isEmpty()) {
        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.freeeed.ep.web.controller.ProcessingController.java

public ModelAndView execute() {
    log.info("request received... ");
    if (!(request instanceof MultipartHttpServletRequest)) {
        valueStack.put("status", "error");

        return new ModelAndView(WebConstants.PROCESS_REQUEST_RESPONSE);
    }/*from w  w  w . ja va 2s  . c  om*/

    MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
    MultipartFile file = multipartRequest.getFile("file");
    String taskId = multipartRequest.getParameter("taskId");

    ProcessingResult result = null;

    try {
        File uploadDirFile = new File(uploadDir);
        uploadDirFile.mkdirs();

        String fileName = uploadDir + File.separator + file.getOriginalFilename();
        File destination = new File(fileName);

        log.info("File transfer started... ");

        file.transferTo(destination);

        NSFTask task = new NSFTask(destination.getAbsolutePath(), workDir);
        result = processor.submitTask(taskId, task);
    } catch (Exception e) {
        log.error("Problem uploading file: ", e);
        result = new ProcessingResult();
        result.setStatus(ProcessingStatus.ERROR);
    }

    Gson gson = new Gson();
    String data = gson.toJson(result);

    valueStack.put("status", data);

    log.info("File submitted for processing!");

    return new ModelAndView(WebConstants.PROCESS_REQUEST_RESPONSE);
}

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

protected List<Path> processArchive(final MultipartFile multipartFile) throws IOException {
    final List<Path> archivePictures = new ArrayList<>(128);

    // We copy the archive in a tmp file
    final File tmpFile = File.createTempFile(multipartFile.getName(), ".tmp");
    multipartFile.transferTo(tmpFile);
    // final InputStream archiveInputStream = multipartFile.getInputStream();
    // Streams.copy(archiveInputStream, new FileOutputStream(tmpFile), true);
    // archiveInputStream.close();

    final Path tmpFilePath = tmpFile.toPath();
    final FileSystem archiveFs = FileSystems.newFileSystem(tmpFilePath, null);

    final Iterable<Path> rootDirs = archiveFs.getRootDirectories();
    for (final Path rootDir : rootDirs) {
        Files.walkFileTree(rootDir, new SimpleFileVisitor<Path>() {

            @Override// ww  w . j a  va  2 s.c  o m
            public FileVisitResult visitFile(final Path path, final BasicFileAttributes attrs)
                    throws IOException {
                final boolean isDirectory = Files.isDirectory(path);

                if (!isDirectory) {
                    final String contentType = Files.probeContentType(path);
                    if (contentType != null && contentType.startsWith("image/")) {
                        archivePictures.add(path);
                    }
                }

                return super.visitFile(path, attrs);
            }
        });
    }

    return archivePictures;
}

From source file:upload.FileService.java

public boolean saveFile(MultipartFile multipartFile) {
    boolean result = false;
    //set the saved location and create a directory location  
    String fileName = multipartFile.getOriginalFilename();
    String location = SAVE_LOCATION;
    File pathFile = new File(location);
    //check if directory exist, if not, create directory  
    if (!pathFile.exists()) {
        pathFile.mkdir();/*from   w ww  .  j a va 2 s . c  o m*/
    }

    //create the actual file  
    pathFile = new File(location + fileName);
    //save the actual file  
    try {
        multipartFile.transferTo(pathFile);
        result = true;
    } catch (IOException e) {
        e.printStackTrace();
    }
    return result;
}

From source file:org.projectbuendia.openmrs.web.controller.ProfileManager.java

/** Handles an uploaded profile. */
private void addProfile(MultipartHttpServletRequest request, ModelMap model) {
    List<String> lines = new ArrayList<>();
    MultipartFile mpf = request.getFile("file");
    if (mpf != null) {
        String message = "";
        String filename = mpf.getOriginalFilename();
        try {//from   w w  w  . jav a  2s.co  m
            File tempFile = File.createTempFile("profile", null);
            mpf.transferTo(tempFile);
            boolean exResult = execute(VALIDATE_CMD, tempFile, lines);
            if (exResult) {
                filename = getNextVersionedFilename(filename);
                File newFile = new File(profileDir, filename);
                FileUtils.moveFile(tempFile, newFile);
                model.addAttribute("success", true);
                message = "Success adding profile: ";
            } else {
                model.addAttribute("success", false);
                message = "Error adding profile: ";
            }
        } catch (Exception e) {
            model.addAttribute("success", false);
            message = "Problem saving uploaded profile: ";
            lines.add(e.getMessage());
            log.error("Problem saving uploaded profile", e);
        } finally {
            model.addAttribute("operation", "add");
            model.addAttribute("message", message + filename);
            model.addAttribute("filename", filename);
            model.addAttribute("output", StringUtils.join(lines, "\n"));
        }
    }
}

From source file:org.shareok.data.documentProcessor.DocumentProcessorUtil.java

public static String saveMultipartFileByTimePath(MultipartFile file, String uploadPath) {
    String uploadedFilePath = null;
    try {/*from w ww .  ja  va 2s. c  o m*/
        String oldFileName = file.getOriginalFilename();
        String extension = DocumentProcessorUtil.getFileExtension(oldFileName);
        oldFileName = DocumentProcessorUtil.getFileNameWithoutExtension(oldFileName);
        //In the future the new file name will also has the user name
        String time = new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss").format(new Date());
        String newFileName = oldFileName + "." + extension;

        if (null != uploadPath) {
            File uploadFolder = new File(uploadPath);
            if (!uploadFolder.exists()) {
                uploadFolder.mkdir();
            }
            File uploadTimeFolder = new File(uploadPath + File.separator + time);
            if (!uploadTimeFolder.exists()) {
                uploadTimeFolder.mkdir();
            }
        }
        uploadedFilePath = uploadPath + File.separator + time + File.separator + newFileName;
        File uploadedFile = new File(uploadedFilePath);
        file.transferTo(uploadedFile);
    } catch (Exception ex) {
        Logger.getLogger(DocumentProcessorUtil.class.getName()).log(Level.SEVERE, null, ex);
    }
    return uploadedFilePath;
}

From source file:com.aboutdata.service.bean.ImageGraphicsServiceImpl.java

@Override
@Deprecated/*  ww w.  j a  v a2  s.  c  o  m*/
public void build(Photos photos, MultipartFile multipartFile) {
    if (multipartFile != null && !multipartFile.isEmpty()) {
        try {
            File tempFile = new File(
                    System.getProperty("java.io.tmpdir") + "/upload_" + multipartFile.getOriginalFilename());
            if (!tempFile.getParentFile().exists()) {
                tempFile.getParentFile().mkdirs();
            }
            multipartFile.transferTo(tempFile);
            //addTask(sourcePath, largePath, mediumPath, thumbnailPath, tempFile, multipartFile.getContentType());
            String path = storageService.upload(tempFile);

            //?? wallhaven?
            //Random r1 = new Random();
            //int num = r1.nextInt(19) + 1;
            //String thumbnail = "http://themes.mediacreed.com/html/synergy/assets/media/galleries/image_gallery/thumbs/thumb" + num + ".jpg";
            //String medium = "http://themes.mediacreed.com/html/synergy/assets/media/galleries/image_gallery/images/image" + num + ".jpg";
            /**
             * EasyImage??
             */
            EasyImage image = new EasyImage(tempFile);
            float width = image.getWidth();
            //??
            int resize = (int) ((200 / width) * 100);
            image.resize(resize);
            //?
            image.saveAs("/tmp/" + tempFile.getName());
            File tempThumbnail = new File("/tmp/" + tempFile.getName());
            String thumbnail = storageService.upload(tempThumbnail);
            //?
            tempThumbnail.delete();

        } catch (IOException | IllegalStateException e) {
            e.printStackTrace();
        }
    }
}

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

@Override
protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object object,
        BindException errors) throws Exception {
    Banner banner = (Banner) object;//from w  w  w .j a  va 2s.  com

    MultipartHttpServletRequest multipart_request = (MultipartHttpServletRequest) request;
    MultipartFile file = multipart_request.getFile("file");
    if (banner.getType().equals(BannerType.Script)) {
        banner.setHash(MD5.asHex(banner.getScript().getBytes()).substring(0, 100));
    }
    if (file != null && file.getSize() > 0 && banner.getType() != BannerType.Script) {

        String fileName = file.getOriginalFilename();
        File bannerFile = new File(bannerDirectory + "/tmp/" + fileName);
        bannerFile.mkdirs();
        file.transferTo(bannerFile);
        String hash = MD5.asHex(MD5.getHash(bannerFile));

        banner.setHash(hash);
        FileUtils.copyFile(bannerFile,
                new File(bannerDirectory + "/" + banner.getHash() + "." + banner.getType().toString()));
        bannerFile.delete();
    } else {
        errors.reject("A file is required");
    }

    return super.onSubmit(request, response, banner, errors);
}

From source file:com.hrm.controller.RegisterController.java

/**
 * author qwc//from  w w  w.j  a v a2 s .co  m
 * 2017413?8:49:23
 * @param request
 * @param file
 * @param url
 * @param num
 * @param Id
 * @param foldername
 * @return
 * @throws IOException
 * ?request.getSession().getServletContext().getRealPath("/")
 */
public static String SaveImg(HttpServletRequest request, MultipartFile file, String url, int num, String Id,
        String foldername) throws IOException {
    String uploadUrl = "C:/" + "HRM/" + "upload/image/" + foldername + "/";
    System.out.println(":" + uploadUrl);
    File dir = new File(uploadUrl);
    if (!dir.exists()) {
        dir.mkdirs();
    }
    url = Id + num + DateUtil.dateToStr(new Date(), DateUtil.DATE_TIME_NO_SLASH) + ".jpg";
    File targetFile = new File(uploadUrl + url);
    /*url="http://localhost:8080/HRM/"+"upload/image/companyinfo"+"/"+url;*/
    uploadUrl = "/HRM/upload/image/" + foldername + "/" + url;
    try {
        file.transferTo(targetFile);
    } catch (IllegalStateException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return uploadUrl;
}

From source file:org.opensprout.osaf.propertyeditor.FilePropertyEditor.java

/** MultipartFile -> File(uploadFolder/filename) */
public void setValue(Object value) {
    if (value instanceof MultipartFile) {
        MultipartFile multipartFile = (MultipartFile) value;

        // if there is no file
        if (multipartFile.isEmpty()) {
            this.logger.debug("Filename: null");
            super.setValue(null);
            return;
        }//from  w  ww  . j a v  a 2  s.  c o  m

        String fileName = makeDuplicationSafeFileName(multipartFile.getOriginalFilename());
        this.logger.debug("Filename : " + fileName);
        String path = uploadDirectory + "/" + fileName;

        // transfer file
        try {
            multipartFile.transferTo(new File(path));
        } catch (IOException e) {
            this.logger.debug("Multipart Error : " + e.getMessage());
            throw new OSAFException("Check upload folder  : [" + uploadDirectory + "]."
                    + "Nested exception is : " + e.getMessage());
        }
        super.setValue(path);
    } else {
        super.setValue(null);
    }
}