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:dicky.controlleradmin.ProductAdminController.java

@RequestMapping(value = "prosesInsert", method = RequestMethod.POST)
public String prosesInsert(HttpServletRequest request, HttpSession session, ModelMap modelMap,
        @RequestParam("fileUpload") MultipartFile[] fileUpload) throws ServletException, IOException {

    if (fileUpload != null && fileUpload.length > 0) {
        for (MultipartFile file : fileUpload) {
            String lokasiUpload = tujuanUpload(session).getAbsolutePath();

            System.out.println("Saving file: " + file.getOriginalFilename());
            Product product = new Product();
            product.setIdProduct(request.getParameter("idproduct"));
            product.setNameProduct(request.getParameter("nama"));
            String price = request.getParameter("price");
            product.setPrice(new BigDecimal(price));
            String idkategori = request.getParameter("idkategori");
            Kategori findId = kategoriService.findId(idkategori);
            product.setKategori(findId);
            product.setFilename(file.getOriginalFilename());
            product.setFiledata(file.getBytes());
            File tujuan = new File(lokasiUpload + File.separator + file.getOriginalFilename());
            file.transferTo(tujuan);
            productService.create(product);
            modelMap.put("products", productService.findAll());

        }//w w  w . j a  v a2  s .c o  m
    }

    return "redirect:../product.html";
}

From source file:org.jasig.portlet.blackboardvcportlet.service.impl.SessionServiceImpl.java

private BlackboardPresentationResponse createSessionPresentation(Session session, ConferenceUser conferenceUser,
        MultipartFile file) {
    final String filename = FilenameUtils.getName(file.getOriginalFilename());

    File multimediaFile = null;/*from w  w w. ja v a  2s  .  c  o  m*/
    try {
        //Transfer the uploaded file to our own temp file so we can use a FileDataSource
        multimediaFile = File.createTempFile(filename, ".tmp", this.tempDir);
        file.transferTo(multimediaFile);

        //Upload the file to BB
        return this.presentationWSDao.uploadPresentation(session.getBbSessionId(), conferenceUser.getUniqueId(),
                filename, "", new DataHandler(new FileDataSource(multimediaFile)));
    } catch (IOException e) {
        throw new RuntimeException("Failed to upload multimedia file '" + filename + "'", e);
    } finally {
        FileUtils.deleteQuietly(multimediaFile);
    }
}

From source file:org.jasig.portlet.blackboardvcportlet.service.impl.SessionServiceImpl.java

private BlackboardMultimediaResponse createSessionMultimedia(Session session, ConferenceUser conferenceUser,
        MultipartFile file) {
    final String filename = FilenameUtils.getName(file.getOriginalFilename());

    File multimediaFile = null;//  w w  w. j  ava 2s  .  co m
    try {
        //Transfer the uploaded file to our own temp file so we can use a FileDataSource
        multimediaFile = File.createTempFile(filename, ".tmp", this.tempDir);
        file.transferTo(multimediaFile);

        //Upload the file to BB
        return this.multimediaWSDao.createSessionMultimedia(session.getBbSessionId(),
                conferenceUser.getUniqueId(), filename, "",
                new DataHandler(new FileDataSource(multimediaFile)));
    } catch (IOException e) {
        throw new RuntimeException("Failed to upload multimedia file '" + filename + "'", e);
    } finally {
        FileUtils.deleteQuietly(multimediaFile);
    }
}

From source file:com.chinalbs.service.impl.FileServiceImpl.java

@Override
public String saveImage(MultipartFile[] multipartFile) {
    String webPath = null;//from w w w .j  a  v a2 s. c om
    if (multipartFile == null || multipartFile.length == 0) {
        return null;
    }
    try {
        for (MultipartFile multiFile : multipartFile) {
            if (multiFile.getSize() > ImageMaxSize) {
                continue;
            }
            String uuid = UUID.randomUUID().toString();
            String sourcePath = uploadPath + File.separator + "src_" + uuid + "."
                    + FilenameUtils.getExtension(multiFile.getOriginalFilename());
            //            webPath = uuid + "." + DEST_EXTENSION;
            webPath = File.separator + "src_" + uuid + "."
                    + FilenameUtils.getExtension(multiFile.getOriginalFilename());
            String storePath = uploadPath + File.separator + uuid + "." + DEST_EXTENSION;
            ;

            File tempFile = new File(System.getProperty("java.io.tmpdir") + File.separator + "upload_"
                    + UUID.randomUUID() + ".tmp");
            if (!tempFile.getParentFile().exists()) {
                tempFile.getParentFile().mkdirs();
            }

            multiFile.transferTo(tempFile);
            proccessImage(tempFile, sourcePath, storePath, licenseImageWidth, licenseImageHeight, true);
        }
    } catch (IllegalStateException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return webPath;
}

From source file:egovframework.rte.tex.gds.service.impl.EgovGoodsServiceImpl.java

/**
 * ? ? ./*from   w  w w  . j  av a 2 s .  c  o  m*/
 * @param request
 * @param goodsVO 
 * @throws Exception
 */
public void updateGoods(GoodsVO goodsVO, final HttpServletRequest request) throws Exception {

    final MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;

    GoodsImageVO[] imageList = new GoodsImageVO[2];
    // extract files
    final Map<String, MultipartFile> files = multiRequest.getFileMap();

    // process files
    String uploadLastPath = fileUploadProperties.getProperty("file.upload.path");

    String uploadPath = request.getSession().getServletContext().getRealPath("/") + uploadLastPath;
    File saveFolder = new File(uploadPath);

    //  ?
    boolean isDir = false;

    if (!saveFolder.exists() || saveFolder.isFile()) {
        saveFolder.mkdirs();
    }

    if (!isDir) {

        Iterator<Entry<String, MultipartFile>> itr = files.entrySet().iterator();
        MultipartFile file;
        String filePath;
        int i = 0; // goodsImage,detailImage  index 
        while (itr.hasNext()) {

            // ??  
            Entry<String, MultipartFile> entry = itr.next();
            file = entry.getValue();

            if (!"".equals(file.getOriginalFilename())) {

                String saveFileName;

                if (i == 0) {
                    saveFileName = goodsVO.getGoodsImageVO().getGoodsImageId();
                } else {
                    saveFileName = goodsVO.getDetailImageVO().getGoodsImageId();
                }

                imageList[i] = new GoodsImageVO(saveFileName, file.getOriginalFilename());
                // ? 
                filePath = uploadPath + "\\" + saveFileName;
                file.transferTo(new File(filePath));
            }
            i++;
        }
    }
    if (imageList[0] != null)
        goodsVO.setGoodsImageVO(imageList[0]);
    if (imageList[1] != null)
        goodsVO.setDetailImageVO(imageList[1]);

    goodsDAO.updateGoods(goodsVO);

}

From source file:de.steilerdev.myVerein.server.model.GridFSRepository.java

public GridFSFile storeClubLogo(MultipartFile clubLogoFile) throws MongoException {
    if (!clubLogoFile.getContentType().startsWith("image")) {
        logger.warn("Trying to store a club logo, which is not an image");
        throw new MongoException("The file needs to be an image");
    } else if (!(clubLogoFile.getContentType().equals("image/jpeg")
            || clubLogoFile.getContentType().equals("image/png"))) {
        logger.warn("Trying to store an incompatible image " + clubLogoFile.getContentType());
        throw new MongoException("The used image is not compatible, please use only PNG or JPG files");
    } else {//from w  w  w. j ava2  s .  c o m
        File clubLogoTempFile = null;
        try {
            clubLogoTempFile = File.createTempFile("tempClubLogo", "png");
            clubLogoTempFile.deleteOnExit();
            if (clubLogoFile.getContentType().equals("image/png")) {
                logger.debug("No need to convert club logo");
                clubLogoFile.transferTo(clubLogoTempFile);
            } else {
                logger.info("Converting club logo file to png");
                //Reading, converting and writing club logo
                ImageIO.write(ImageIO.read(clubLogoFile.getInputStream()), clubLogoFileFormat,
                        clubLogoTempFile);
            }

            //Deleting current file
            deleteCurrentClubLogo();

            try (FileInputStream clubLogoStream = new FileInputStream(clubLogoTempFile)) {
                logger.debug("Saving club logo");
                //Saving file
                return gridFS.store(clubLogoStream, clubLogoFileName, clubLogoFileFormatMIME);
            }
        } catch (IOException e) {
            e.printStackTrace();
            throw new MongoException("Unable to store file");
        } finally {
            if (clubLogoTempFile != null) {
                clubLogoTempFile.delete();
            }
        }
    }
}

From source file:fr.treeptik.cloudunit.controller.ModuleController.java

@RequestMapping(value = "/{applicationName}/{moduleName}/initData", method = RequestMethod.POST, consumes = {
        "multipart/form-data" })
@ResponseBody// ww w.ja  v  a2  s . c  o  m
public JsonResponse deploy(@RequestPart("file") MultipartFile fileUpload,
        @PathVariable final String applicationName, @PathVariable final String moduleName,
        HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServiceException, CheckException {

    logger.info("initDb : applicationName = " + applicationName + ", moduleName = " + moduleName);

    User user = authentificationUtils.getAuthentificatedUser();
    Application application = applicationService.findByNameAndUser(user, applicationName);

    // We must be sure there is no running action before starting new one
    this.authentificationUtils.canStartNewAction(user, application, locale);

    File file = null;
    try {

        // Application occupe
        applicationService.setStatus(application, Status.PENDING);

        file = File.createTempFile("script-", fileUpload.getOriginalFilename());
        fileUpload.transferTo(file);

        moduleService.initDb(user, applicationName, moduleName, file);

    } catch (IOException e) {
        throw new ServiceException("initDb Error while creating file", e);
    } finally {
        applicationService.setStatus(application, Status.START);
    }
    return new HttpOk();
}

From source file:com.pantuo.service.impl.AttachmentServiceImpl.java

public String saveAttachmentSimple(HttpServletRequest request) throws BusinessException {
    StringBuffer r = new StringBuffer();
    try {//from   ww  w.j a v  a2  s . c  o m
        CustomMultipartResolver multipartResolver = new CustomMultipartResolver(
                request.getSession().getServletContext());
        if (multipartResolver.isMultipart(request)) {
            String path = request.getSession().getServletContext()
                    .getRealPath(com.pantuo.util.Constants.FILE_UPLOAD_DIR).replaceAll("WEB-INF", "");
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
            Iterator<String> iter = multiRequest.getFileNames();
            while (iter.hasNext()) {
                MultipartFile file = multiRequest.getFile(iter.next());
                if (file != null && !file.isEmpty()) {
                    String oriFileName = file.getOriginalFilename();
                    if (StringUtils.isNoneBlank(oriFileName)) {
                        String storeName = GlobalMethods
                                .md5Encrypted((System.currentTimeMillis() + oriFileName).getBytes());
                        Pair<String, String> p = FileHelper.getUploadFileName(path,
                                storeName += FileHelper.getFileExtension(oriFileName, true));
                        File localFile = new File(p.getLeft());
                        file.transferTo(localFile);
                        if (r.length() == 0) {
                            r.append(p.getRight());
                        } else {
                            r.append(";" + p.getRight());
                        }
                    }
                }
            }
        }
        return r.toString();
    } catch (Exception e) {
        log.error("saveAttachmentSimple", e);
        throw new BusinessException("saveAttachment-error", e);
    }
}

From source file:com.igame.app.controller.Image2Controller.java

@RequestMapping(value = "/upload", method = RequestMethod.POST)
public @ResponseBody Map upload(MultipartHttpServletRequest request, HttpServletResponse response) {
    // HttpSession
    SecUser user = (SecUser) request.getSession().getAttribute("user");
    long appid = user.getAppid();
    log.debug("uploadPost called appid:{}" + appid);
    Iterator<String> itr = request.getFileNames();
    MultipartFile mpf;
    List<Image> list = new LinkedList<>();

    while (itr.hasNext()) {
        mpf = request.getFile(itr.next());
        log.debug("Uploading {}", mpf.getOriginalFilename());

        long id = IDGenerator.getKey();
        // String newFilenameBase = String.valueOf(id);
        String originalFileExtension = mpf.getOriginalFilename()
                .substring(mpf.getOriginalFilename().lastIndexOf("."));
        String newFilename = id + originalFileExtension;
        String storageDirectory = fileUploadDirectory;
        String contentType = mpf.getContentType();

        File newFile = new File(storageDirectory + "/" + "app-" + appid + "/" + newFilename);

        if (!newFile.getParentFile().exists()) {
            log.debug(" {}" + newFile.getParentFile().getPath());
            newFile.getParentFile().mkdirs();
        }// w w  w .  j av a2s .  c  om

        try {
            mpf.transferTo(newFile);

            BufferedImage thumbnail = Scalr.resize(ImageIO.read(newFile), 150);
            String thumbnailFilename = id + "-thumbnail.png";
            File thumbnailFile = new File(storageDirectory + "/" + "app-" + appid + "/" + thumbnailFilename);
            ImageIO.write(thumbnail, "png", thumbnailFile);

            Image image = new Image();
            image.setId(id);
            image.setAppid(appid);
            image.setName(mpf.getOriginalFilename());
            image.setThumbnailFilename(thumbnailFilename);
            image.setNewFilename(newFilename);
            image.setContentType(contentType);
            image.setSize(mpf.getSize());
            image.setThumbnailSize(thumbnailFile.length());
            image = imageService.create(image);

            image.setUrl("app-" + appid + "/" + newFilename);
            image.setThumbnailUrl("app-" + appid + "/" + thumbnailFilename);
            image.setDeleteUrl("delete/" + image.getId());
            image.setDeleteType("DELETE");

            list.add(image);

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

    }

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