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.nts.alphamaleWeb.controller.ServiceController.java

@RequestMapping(value = "/installApp", method = RequestMethod.POST)
@ResponseBody// ww w. j a v  a  2  s  .  co m
public String installApp(@RequestParam String devJson, @RequestPart("file_apk") MultipartFile mpf) {

    ResultBody<String> result = new ResultBody<String>();
    List<String> devices = getDeivceListFromString(devJson);
    Gson gson = new GsonBuilder().setPrettyPrinting().create();
    String path = mpf.getOriginalFilename();
    try {
        if (mpf.isEmpty()) {
            result.setCode(Code.F400);
        } else {
            File file = new File(path);
            mpf.transferTo(new File(file.getAbsolutePath()));
            String results = alphamaleController.installApp(devices, true, file.getAbsolutePath());
            String resultJson = gson.toJson(results);
            result.setCode(Code.OK, resultJson);
        }
    } catch (IOException e) {
        e.printStackTrace();
        result.setCode(Code.F400);
    }

    return result.toJson();
}

From source file:controllers.ProcessController.java

@RequestMapping("management/staffs/add")
public ModelAndView staffs(@RequestParam("name") String name, @RequestParam("gender") String genderString,
        @RequestParam("birthday") String birthdayString, @RequestParam("avatar") MultipartFile avatar,
        @RequestParam("email") String email, @RequestParam("phone") String phone,
        @RequestParam("salary") String salaryString, @RequestParam("notes") String notes,
        @RequestParam("depart") String departId) throws IOException {
    String avatarFileName = "default-avatar.png";
    if (!avatar.isEmpty()) {
        String avatarPath = context.getRealPath("/resources/images/" + avatar.getOriginalFilename());
        avatar.transferTo(new File(avatarPath));
        avatarFileName = new File(avatarPath).getName();
    }//from w w  w  .jav  a 2s. co  m
    StaffsDAO staffsDAO = new StaffsDAO();
    staffsDAO.addStaff(name, genderString, birthdayString, avatarFileName, email, phone, salaryString, notes,
            departId);
    return new ModelAndView("redirect:../staffs.htm");
}

From source file:com.ylife.goods.model.UploadImgUpyun.java

/**
 * ??//from   ww w .j ava2s .c  om
 * 
 * @param muFile
 * @return Map?oldimgsmall?
 */
public Map<String, String> uploadForOldAndSmall(MultipartFile muFile, UpyunConf upConf) {
    Map<String, String> imgMap = new HashMap<String, String>();
    if (muFile != null && muFile.getSize() != 0) {
        // ??java?
        @SuppressWarnings("unused")
        boolean flag = false;

        // ???????????
        String fileNamess = UploadImgCommon.getPicNamePathSuffix();

        File file = new File(fileNamess);
        try {
            muFile.transferTo(file);
            if (upConf != null) {
                YunBean yb = new YunBean();
                yb.setBucketName(upConf.getBucketName());
                yb.setPassword(upConf.getPassWord());
                yb.setUserName(upConf.getUserName());
                UpYunUtil.yunUp(fileNamess, UploadImgCommon.prefix, yb, UploadImgCommon.suffix);
                // ??
                //LOGGER.debug(LOGGERINFO1 + upConf.getUrlPath() + UploadImgCommon.prefix + UploadImgCommon.suffix);
                imgMap.put(OLDIMG, upConf.getUrlPath() + UploadImgCommon.prefix + UploadImgCommon.suffix);

                // ???
                //LOGGER.debug("==========56?" + upConf.getUrlPath() + UploadImgCommon.prefix + UploadImgCommon.suffix + "!" + SMALL);
                imgMap.put("small",
                        upConf.getUrlPath() + UploadImgCommon.prefix + UploadImgCommon.suffix + "!" + SMALL);

            } else {
                flag = true;
            }
        } catch (IllegalStateException e) {
            //LOGGER.error(LOGGERINFO4, e);
            flag = true;
        } catch (IOException e) {
            //LOGGER.error(LOGGERINFO4, e);
            flag = true;
        } catch (Exception e) {
            //LOGGER.error(LOGGERINFO4, e);
            flag = true;
        }
        return imgMap;
    } else {
        return null;
    }
}

From source file:com.ylife.goods.model.UploadImgUpyun.java

/**
 * ????/*  w w w. ja  v a 2  s  .  c  o m*/
 * 
 * @param muFile
 * @return Map?4oldimg0??1?2
 */
public Map<String, String> uploadForABCSize(MultipartFile muFile, UpyunConf upConf) {
    Map<String, String> imgMap = new HashMap<String, String>();
    if (muFile != null && muFile.getSize() != 0) {
        // ??java?
        @SuppressWarnings("unused")
        boolean flag = false;

        // ???????????
        String fileNamess = UploadImgCommon.getPicNamePathSuffix();

        File file = new File(fileNamess);
        try {
            muFile.transferTo(file);
            if (upConf != null) {
                YunBean yb = new YunBean();
                yb.setBucketName(upConf.getBucketName());
                yb.setPassword(upConf.getPassWord());
                yb.setUserName(upConf.getUserName());
                UpYunUtil.yunUp(fileNamess, UploadImgCommon.prefix, yb, UploadImgCommon.suffix);
                // ??
                //LOGGER.debug(LOGGERINFO1 + upConf.getUrlPath() + UploadImgCommon.prefix + UploadImgCommon.suffix);
                imgMap.put(OLDIMG, upConf.getUrlPath() + UploadImgCommon.prefix + UploadImgCommon.suffix);

                // ??85
                int[] widths = UploadImgCommon.getImgSetOut85(imageSetMapper.queryImageSet());
                UploadImgCommon.sortWidth(widths);
                for (int i = 0; i < widths.length; i++) {
                    // ??
                    //LOGGER.debug(LOGGERINFO2 + widths[i] + LOGGERINFO3 + upConf.getUrlPath() + UploadImgCommon.prefix + UploadImgCommon.suffix + "!" + widths[i]);
                    imgMap.put(i + "", upConf.getUrlPath() + UploadImgCommon.prefix + UploadImgCommon.suffix
                            + "!" + widths[i]);
                }

            } else {
                flag = true;
            }
        } catch (IllegalStateException e) {
            //LOGGER.error(LOGGERINFO4, e);
            flag = true;
        } catch (IOException e) {
            //LOGGER.error(LOGGERINFO4, e);
            flag = true;
        } catch (Exception e) {
            // LOGGER.error(LOGGERINFO4, e);
            flag = true;
        }
        return imgMap;
    } else {
        return null;
    }
}

From source file:com.ylife.goods.model.UploadImgUpyun.java

/**
 * ????//from   w  w  w. ja  va2 s  .c  o m
 * 
 * @param muFile
 * @return Map?key
 */
public Map<String, String> uploadForAllSize(MultipartFile muFile, UpyunConf upConf) {
    Map<String, String> imgMap = new HashMap<String, String>();
    if (muFile != null && muFile.getSize() != 0) {
        // ??java?
        @SuppressWarnings("unused")
        boolean flag = false;

        // ???????????
        String fileNamess = UploadImgCommon.getPicNamePathSuffix();

        File file = new File(fileNamess);
        try {
            muFile.transferTo(file);
            if (upConf != null) {
                YunBean yb = new YunBean();
                yb.setBucketName(upConf.getBucketName());
                yb.setPassword(upConf.getPassWord());
                yb.setUserName(upConf.getUserName());
                UpYunUtil.yunUp(fileNamess, UploadImgCommon.prefix, yb, UploadImgCommon.suffix);
                // ??
                //LOGGER.debug(LOGGERINFO1 + upConf.getUrlPath() + UploadImgCommon.prefix + UploadImgCommon.suffix);
                imgMap.put(OLDIMG, upConf.getUrlPath() + UploadImgCommon.prefix + UploadImgCommon.suffix);

                // ??
                int[] widths = UploadImgCommon.getImgSet(imageSetMapper.queryImageSet());
                UploadImgCommon.sortWidth(widths);
                for (int i = 0; i < widths.length; i++) {
                    // ??
                    //LOGGER.debug(LOGGERINFO2 + widths[i] + LOGGERINFO3 + upConf.getUrlPath() + UploadImgCommon.prefix + UploadImgCommon.suffix + "!" + widths[i]);
                    imgMap.put(widths[i] + "", upConf.getUrlPath() + UploadImgCommon.prefix
                            + UploadImgCommon.suffix + "!" + widths[i]);
                }

            } else {
                flag = true;
            }
        } catch (IllegalStateException e) {
            //LOGGER.error(LOGGERINFO4, e);
            flag = true;
        } catch (IOException e) {
            //LOGGER.error(LOGGERINFO4, e);
            flag = true;
        } catch (Exception e) {
            //LOGGER.error(LOGGERINFO4, e);
            flag = true;
        }
        return imgMap;
    } else {
        return null;
    }
}

From source file:de.interactive_instruments.etf.webapp.controller.TestObjectController.java

@RequestMapping(value = "/testobjects/add-file-to", method = RequestMethod.POST)
public String addFileTestData(@ModelAttribute("testObject") @Valid TestObjectDto testObject,
        BindingResult result, MultipartHttpServletRequest request, Model model)
        throws IOException, URISyntaxException, StoreException, ParseException, NoSuchAlgorithmException {
    if (SUtils.isNullOrEmpty(testObject.getLabel())) {
        throw new IllegalArgumentException("Label is empty");
    }//from w  ww. j a  va  2s  .com

    if (result.hasErrors()) {
        return showCreateDoc(model, testObject);
    }

    final GmlAndXmlFilter filter;
    final String regex = testObject.getProperty("regex");
    if (regex != null && !regex.isEmpty()) {
        filter = new GmlAndXmlFilter(new RegexFileFilter(regex));
    } else {
        filter = new GmlAndXmlFilter();
    }

    // Transfer uploaded data
    final MultipartFile multipartFile = request.getFile("testObjFile");
    if (multipartFile != null && !multipartFile.isEmpty()) {
        // Transfer file to tmpUploadDir
        final IFile testObjFile = this.tmpUploadDir
                .secureExpandPathDown(testObject.getLabel() + "_" + multipartFile.getOriginalFilename());
        testObjFile.expectFileIsWritable();
        multipartFile.transferTo(testObjFile);
        final String type;
        try {
            type = MimeTypeUtils.detectMimeType(testObjFile);
            if (!type.equals("application/xml") && !type.equals("application/zip")) {
                throw new IllegalArgumentException(type + " is not supported");
            }
        } catch (Exception e) {
            result.reject("l.upload.invalid", new Object[] { e.getMessage() }, "Unable to use file: {0}");
            return showCreateDoc(model, testObject);
        }

        // Create directory for test data file
        final IFile testObjectDir = testDataDir
                .secureExpandPathDown(testObject.getLabel() + ".upl." + getSimpleRandomNumber(4));
        testObjectDir.ensureDir();

        if (type.equals("application/zip")) {
            // Unzip files to test directory
            try {
                testObjFile.unzipTo(testObjectDir, filter);
            } catch (IOException e) {
                try {
                    testObjectDir.delete();
                } catch (Exception de) {
                    ExcUtils.supress(de);
                }
                result.reject("l.decompress.failed", new Object[] { e.getMessage() },
                        "Unable to decompress file: {0}");
                return showCreateDoc(model, testObject);
            } finally {
                // delete zip file
                testObjFile.delete();
            }
        } else {
            // Move XML to test directory
            testObjFile.copyTo(testObjectDir.getPath() + File.separator + multipartFile.getOriginalFilename());
        }
        testObject.addResource("data", testObjectDir.toURI());
        testObject.getProperties().setProperty("uploaded", "true");
    } else {
        final URI resURI = testObject.getResourceById("data");
        if (resURI == null) {
            throw new StoreException("Workflow error. Data path resource not set.");
        }
        final IFile absoluteTestObjectDir = testDataDir.secureExpandPathDown(resURI.getPath());
        testObject.getResources().clear();
        testObject.getResources().put(EidFactory.getDefault().createFromStrAsStr("data"),
                absoluteTestObjectDir.toURI());

        // Check if file exists
        final IFile sourceDir = new IFile(new File(testObject.getResourceById("data")));
        try {
            sourceDir.expectDirIsReadable();
        } catch (Exception e) {
            result.reject("l.testObject.testdir.insufficient.rights", new Object[] { e.getMessage() },
                    "Insufficient rights to read directory: {0}");
            return showCreateDoc(model, testObject);
        }
        testObject.getProperties().setProperty("uploaded", "false");
    }

    final FileHashVisitor v = new FileHashVisitor(filter);
    Files.walkFileTree(new File(testObject.getResourceById("data")).toPath(),
            EnumSet.of(FileVisitOption.FOLLOW_LINKS), 5, v);

    if (v.getFileCount() == 0) {
        if (regex != null && !regex.isEmpty()) {
            result.reject("l.testObject.regex.null.selection", new Object[] { regex },
                    "No files were selected with the regular expression \"{0}\"!");
        } else {
            result.reject("l.testObject.testdir.no.xml.gml.found",
                    "No file were found in the directory with a gml or xml file extension");
        }
        return showCreateDoc(model, testObject);
    }
    VersionDataDto vd = new VersionDataDto();
    vd.setItemHash(v.getHash());
    testObject.getProperties().setProperty("files", String.valueOf(v.getFileCount()));
    testObject.getProperties().setProperty("size", String.valueOf(v.getSize()));
    testObject.getProperties().setProperty("sizeHR", FileUtils.byteCountToDisplaySize(v.getSize()));
    testObject.setVersionData(vd);

    testObject.setId(EidFactory.getDefault().createRandomUuid());

    testObjStore.create(testObject);

    return "redirect:/testobjects";
}

From source file:com.artivisi.belajar.restful.ui.controller.ApplicationConfigController.java

@RequestMapping(value = "/config/upload", method = RequestMethod.POST)
@ResponseBody//www  .  ja v  a  2 s  .c  o  m
public List<Map<String, String>> testUpload(
        @RequestParam(value = "uploadedfiles[]") List<MultipartFile> daftarFoto) throws Exception {

    logger.debug("Jumlah file yang diupload {}", daftarFoto.size());

    List<Map<String, String>> hasil = new ArrayList<Map<String, String>>();

    for (MultipartFile multipartFile : daftarFoto) {
        logger.debug("Nama File : {}", multipartFile.getName());
        logger.debug("Nama File Original : {}", multipartFile.getOriginalFilename());
        logger.debug("Ukuran File : {}", multipartFile.getSize());

        Map<String, String> keterangan = new HashMap<String, String>();
        keterangan.put("Nama File", multipartFile.getOriginalFilename());
        keterangan.put("Ukuran File", Long.valueOf(multipartFile.getSize()).toString());
        keterangan.put("Content Type", multipartFile.getContentType());
        keterangan.put("UUID", UUID.randomUUID().toString());
        File temp = File.createTempFile("xxx", "xxx");
        multipartFile.transferTo(temp);
        keterangan.put("MD5", createMD5Sum(temp));
        hasil.add(keterangan);
    }

    return hasil;
}

From source file:com.sunflower.petal.controller.ImageController.java

@RequestMapping(value = "/upload", method = RequestMethod.POST)
public @ResponseBody Map upload(MultipartHttpServletRequest request, HttpServletResponse response) {
    log.debug("uploadPost called");
    Iterator<String> itr = request.getFileNames();
    MultipartFile mpf;
    List<Image> list = new LinkedList<Image>();

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

        String newFilenameBase = UUID.randomUUID().toString();
        String originalFileExtension = mpf.getOriginalFilename()
                .substring(mpf.getOriginalFilename().lastIndexOf("."));
        String newFilename = newFilenameBase + originalFileExtension;
        String storageDirectory = fileUploadDirectory;
        String contentType = mpf.getContentType();

        File newFile = new File(storageDirectory + "/" + newFilename);
        try {/*from w  w w  . j  a v a 2 s.c  o m*/
            mpf.transferTo(newFile);

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

            Image image = new Image();
            image.setName(mpf.getOriginalFilename());
            image.setThumbnailFilename(thumbnailFilename);
            image.setNewFilename(newFilename);
            image.setContentType(contentType);
            image.setSize(mpf.getSize());
            image = imageService.create(image);

            image.setUrl("/picture/" + image.getId());
            image.setThumbnailUrl("/thumbnail/" + image.getId());
            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<String, Object>();
    files.put("files", list);
    return files;
}

From source file:eu.scidipes.toolkits.pawebapp.web.AdminController.java

@RequestMapping(value = "/templates", method = RequestMethod.POST)
public String saveTemplate(final RedirectAttributes redirectAttrs, final String processorName,
        @RequestPart(value = "source") final MultipartFile sourceFile) {

    final PreservationDatasourceProcessor processor = SourceProcessorManager.INSTANCE.getProcessors()
            .get(processorName);/* www  . j a va  2 s  .c  o  m*/

    final StringBuilder destinationPath = new StringBuilder();
    destinationPath.append(SOURCE_ROOT_PATH + File.separatorChar);
    destinationPath.append(processor.getClass().getSimpleName() + File.separatorChar);
    destinationPath.append(sourceFile.getOriginalFilename());

    final File destination = new File(destinationPath.toString());

    if (destination.exists()) {
        redirectAttrs.addFlashAttribute("errorKey", SAVE_FAIL_FILE_EXISTS);
        return "redirect:/admin/templates/";
    }

    try {
        sourceFile.transferTo(destination);
        final FormsBundle bundle = processor.sourceToBundle(destination);
        ((FormsBundleImpl) bundle).setTemplateSource(destination.getName());
        FormBundleManager.addBundle(bundle);

        LOG.info("Created new template bundle for processor: {}", processor.getName());

    } catch (final IOException | PreservationException e) {

        LOG.warn("Exception encountered creating bundle from: {}, deleting file: {}.", destination,
                Boolean.valueOf(destination.delete()));

        LOG.error(e.toString(), e);
        redirectAttrs.addFlashAttribute("errorKey", SAVE_FAIL);
        return "redirect:/admin/templates/";
    }

    redirectAttrs.addFlashAttribute("msgKey", SAVE_SUCCESS);
    return "redirect:/admin/templates/";
}

From source file:org.openmrs.module.custombranding.web.controller.CustomBrandingController.java

@Override
protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object command,
        BindException errors) throws Exception {
    String fileSysLocation = request.getRealPath("/");
    String messageFileLocation = fileSysLocation + File.separator + "WEB-INF" + File.separator
            + "messages.properties";
    HttpSession session = request.getSession();

    if (request.getParameter("action") != null) {
        if (request.getParameter("id") != null) {
            if (request.getParameter("id").equals("largeLogo")) {
                if (new File(fileSysLocation + largeLogo + ".orig").exists()) {
                    FileUtils.copyFile(new File(fileSysLocation + largeLogo + ".orig"),
                            new File(fileSysLocation + largeLogo));
                    session.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "Back to default large logo");
                }// w w  w .  jav  a  2 s . c o  m
            } else if (request.getParameter("id").equals("smallLogo")) {
                if (new File(fileSysLocation + smallLogo + ".orig").exists()) {
                    FileUtils.copyFile(new File(fileSysLocation + smallLogo + ".orig"),
                            new File(fileSysLocation + smallLogo));
                    session.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "Back to default small logo");
                }
            } else if (request.getParameter("id").equals("textLogo")) {
                if (new File(fileSysLocation + textLogo + ".orig").exists()) {
                    FileUtils.copyFile(new File(fileSysLocation + textLogo + ".orig"),
                            new File(fileSysLocation + textLogo));
                    session.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "Back to default text logo");
                }
            } else if (request.getParameter("id").equals("messageFile")) {
                if (new File(messageFileLocation + ".orig").exists()) {
                    FileUtils.copyFile(new File(messageFileLocation + ".orig"), new File(messageFileLocation));
                    session.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "Back to default messages");
                }
            } else if (request.getParameter("id").equals("faviconFile")) {
                if (new File(fileSysLocation + favicon + ".orig").exists()) {
                    FileUtils.copyFile(new File(fileSysLocation + favicon + ".orig"),
                            new File(fileSysLocation + favicon));
                    session.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "Back to default favicon");
                }
            } else if (request.getParameter("id").equals("iconFile")) {
                if (new File(fileSysLocation + icon + ".orig").exists()) {
                    FileUtils.copyFile(new File(fileSysLocation + icon + ".orig"),
                            new File(fileSysLocation + icon));
                    session.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "Back to default icon");
                }
            }
        }
    } else {
        try {
            FileUploadBean bean = (FileUploadBean) command;
            MultipartFile largeLogoFile = bean.getLargeLogoFile();
            MultipartFile smallLogoFile = bean.getSmallLogoFile();
            MultipartFile textLogoFile = bean.getTextLogoFile();
            MultipartFile messageFile = bean.getMessageFile();
            MultipartFile faviconFile = bean.getFaviconFile();
            MultipartFile iconFile = bean.getIconFile();

            String orgUrlStr = bean.getOrgUrl();

            if (largeLogoFile != null) {
                FileUtils.copyFile(new File(fileSysLocation + largeLogo),
                        new File(fileSysLocation + largeLogo + ".orig"));
                largeLogoFile.transferTo(new File(fileSysLocation + largeLogo));
                session.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "Successfully replaced large logo");
            } else if (smallLogoFile != null) {
                FileUtils.copyFile(new File(fileSysLocation + smallLogo),
                        new File(fileSysLocation + smallLogo + ".orig"));
                smallLogoFile.transferTo(new File(fileSysLocation + smallLogo));
                session.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "Successfully replaced small logo");
            } else if (textLogoFile != null) {
                FileUtils.copyFile(new File(fileSysLocation + textLogo),
                        new File(fileSysLocation + textLogo + ".orig"));
                textLogoFile.transferTo(new File(fileSysLocation + textLogo));
                session.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "Successfully replaced text logo");
            } else if (messageFile != null) {
                FileUtils.copyFile(new File(messageFileLocation), new File(messageFileLocation + ".orig"));
                messageFile.transferTo(new File(messageFileLocation));
                session.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "Successfully replaced messages file");
            } else if (faviconFile != null) {
                FileUtils.copyFile(new File(fileSysLocation + favicon),
                        new File(fileSysLocation + favicon + ".orig"));
                faviconFile.transferTo(new File(fileSysLocation + favicon));
                session.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "Successfully replaced favicon file");
            } else if (iconFile != null) {
                FileUtils.copyFile(new File(fileSysLocation + icon),
                        new File(fileSysLocation + icon + ".orig"));
                iconFile.transferTo(new File(fileSysLocation + icon));
                session.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "Successfully replaced favicon file");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    return new ModelAndView(new RedirectView(request.getContextPath() + getSuccessView()));
}