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.yqboots.fss.web.controller.FileItemController.java

@PreAuthorize(FileItemPermissions.WRITE)
@RequestMapping(value = WebKeys.MAPPING_ROOT, method = RequestMethod.POST)
public String update(@Valid @ModelAttribute(WebKeys.MODEL) final FileUploadForm form,
        @PageableDefault final Pageable pageable, final BindingResult bindingResult, final ModelMap model)
        throws IOException {
    new FileUploadFormValidator().validate(form, bindingResult);
    if (bindingResult.hasErrors()) {
        model.addAttribute(WebKeys.PAGE, fileItemManager.findByPath(StringUtils.EMPTY, pageable));
        return VIEW_HOME;
    }//from  w  w w  .  j a v  a 2  s.  c  om

    final MultipartFile file = form.getFile();
    final String path = form.getPath();
    final boolean overrideExisting = form.isOverrideExisting();

    final Path destination = Paths
            .get(fileItemManager.getFullPath(path) + File.separator + file.getOriginalFilename());
    if (Files.exists(destination) && overrideExisting) {
        file.transferTo(destination.toFile());
    } else {
        Files.createDirectories(destination.getParent());
        Files.createFile(destination);
        file.transferTo(destination.toFile());
    }

    model.clear();
    return REDIRECT_VIEW_PATH;
}

From source file:net.risesoft.soa.asf.web.controller.SystemController.java

@RequestMapping({ "uploadLicense.do" })
@ResponseBody// w  w  w  .  j  a  v a2  s  .  c  om
public String uploadLicense(MultipartRequest multipartRequest) {
    if (!(this.bundleHelper.isDevMode())) {
        MultipartFile multipartFile = multipartRequest.getFile("licenseFile");

        File licenseFile = new File(
                System.getProperty("user.dir") + "/../license/" + multipartFile.getOriginalFilename());
        try {
            multipartFile.transferTo(licenseFile);
            InputStream istream = null;
            try {
                istream = new FileInputStream(licenseFile);
                if (!(this.checkLicense.check(istream)))
                    throw new RuntimeException("License .");
            } finally {
                IOUtils.closeQuietly(istream);
            }
            IOUtils.closeQuietly(istream);

            File licensePath = licenseFile.getParentFile();
            if (licensePath.isDirectory()) {
                File[] files = licensePath.listFiles();
                for (File f : files) {
                    if ((!(f.isFile())) || (f.equals(licenseFile)))
                        continue;
                    f.delete();
                }
            }

            if (!(this.checkLicense.refresh()))
                throw new RuntimeException("License .");
        } catch (Exception ex) {
            log.error(" License : " + ex.getMessage(), ex);
            if (licenseFile.exists()) {
                licenseFile.delete();
            }
            return "{success:false, msg:'" + ex.getMessage() + "'}";
        }
        return "{success:true, msg:' License ?.'}";
    }
    return "{success:false, msg:' License ???.'}";
}

From source file:uk.ac.bbsrc.tgac.browser.web.UploadController.java

public void uploadFile(Class type, String qualifier, MultipartFile fileItem) throws IOException {
    log.info("uploadfile 1.1");

    File dir = new File(filesManager.getFileStorageDirectory() + File.separator
            + type.getSimpleName().toLowerCase() + File.separator + qualifier);
    if (filesManager.checkDirectory(dir, true)) {
        log.info("Attempting to store " + dir.toString() + File.separator + fileItem.getOriginalFilename());
        fileItem.transferTo(
                new File(dir + File.separator + fileItem.getOriginalFilename().replaceAll("\\s", "_")));
    } else {//from   w w w  .j ava 2 s. c  om
        throw new IOException(
                "Cannot upload file - check that the directory specified in miso.properties exists and is writable");
    }
    log.info("uploadfile 1.2");

}

From source file:cs545.proj.controller.MemberController.java

@RequestMapping(value = "/new", method = RequestMethod.POST)
public String memberUpdateWithLicense(@Valid @ModelAttribute("editMember") Member editMember,
        BindingResult result, HttpSession session) throws IllegalStateException, IOException {
    if (result.hasErrors()) {
        return "editMemberTile";
    }//  w  w  w. j a va 2  s  . co  m

    MultipartFile licenseFile = editMember.getLicenseMultipart();
    if ((licenseFile != null) && (!licenseFile.isEmpty())) {
        String newFilename = sdf.format(new Date()) + licenseFile.getOriginalFilename();
        String rootDirectory = session.getServletContext().getRealPath("/");
        licenseFile.transferTo(new File(rootDirectory + licensePath + newFilename));
        editMember.setLicenseFileName(newFilename);
    }

    Member savedMember = memberService.saveOrMerge(editMember);
    Set<Category> categorySet = new HashSet<Category>();
    for (Category category : savedMember.getSelectedCategories()) {
        categorySet.add(category);
    }
    for (Category category : categorySet) {
        savedMember.removeCategory(category);
    }
    List<Integer> checkedIDs = editMember.getCheckedCategoryIDs();
    if (checkedIDs != null) {
        for (Integer categoryId : checkedIDs) {
            savedMember.addCategory(categoryService.getCategoryById(categoryId));
        }
    }
    savedMember = memberService.saveOrMerge(savedMember);
    return "redirect:/member/detail";
}

From source file:controllers.ConstructorController.java

@RequestMapping("/uploadTemplateElement")
public String uploadTemplateElement(HttpServletRequest request, Map<String, Object> model,
        @RequestParam(value = "templateElem", required = false) MultipartFile templateElem) throws IOException {

    String sid = request.getSession().getId();

    String path = "/usr/local/tomcat/tomcat/webapps/ROOT/public/constructor/" + sid + "/";

    int i = 0;/*  w  ww.  ja va  2s .  c  om*/
    File file = new File(path);
    if (!file.exists()) {
        file.mkdirs();
    }

    while (file.exists()) {
        file = new File(path + (i++));
    }
    templateElem.transferTo(file);

    //return "redirect:/Constructor/show";
    return "redirect:/Constructor/show";
}

From source file:it.cilea.osd.jdyna.web.controller.ImportConfigurazione.java

/** Performa l'import da file xml di configurazioni di oggetti;
 *  Sull'upload del file la configurazione dell'oggetto viene caricato come contesto di spring
 *  e salvate su db.//from  ww w  .j  a  v a  2s. co  m
 */
@Override
protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object object,
        BindException errors) throws RuntimeException, IOException {

    FileUploadConfiguration bean = (FileUploadConfiguration) object;
    MultipartFile file = (CommonsMultipartFile) bean.getFile();
    File a = null;

    //creo il file temporaneo che sara' caricato come contesto di spring per caricare la configurazione degli oggetti
    a = File.createTempFile("jdyna", ".xml", new File(path));
    file.transferTo(a);

    ApplicationContext context = null;
    try {
        context = new FileSystemXmlApplicationContext(new String[] { "file:" + a.getAbsolutePath() },
                getApplicationContext());

    } catch (XmlBeanDefinitionStoreException exc) {
        //cancello il file dalla directory temporanea
        logger.warn("Errore nell'importazione della configurazione dal file: " + file.getOriginalFilename(),
                exc);
        a.delete();
        saveMessage(request, getText("action.file.nosuccess.upload", new Object[] { exc.getMessage() },
                request.getLocale()));
        return new ModelAndView(getErrorView());
    }
    //cancello il file dalla directory temporanea
    a.delete();
    String[] tpDefinitions = context.getBeanNamesForType(tpClass);
    //la variabile i conta le tipologie caricate con successo
    int i = 0;
    //la variabile j conta le tipologie non caricate
    int j = 0;
    for (String tpNameDefinition : tpDefinitions) {
        try {
            TP tipologiaDaImportare = (TP) context.getBean(tpNameDefinition);
            applicationService.saveOrUpdate(tpClass, tipologiaDaImportare);
        } catch (Exception ecc) {
            saveMessage(request, getText("action.file.nosuccess.metadato.upload",
                    new Object[] { ecc.getMessage() }, request.getLocale()));
            j++;
            i--;
        }
        i++;
    }

    String[] areeDefinitions = context.getBeanNamesForType(areaClass);
    int w = 0;
    int v = 0;
    for (String areaNameDefinition : areeDefinitions) {
        try {
            A areaDaImportare = (A) context.getBean(areaNameDefinition);
            applicationService.saveOrUpdate(areaClass, areaDaImportare);
        } catch (Exception ecc) {
            saveMessage(request, getText("action.file.nosuccess.metadato.upload",
                    new Object[] { ecc.getMessage() }, request.getLocale()));
            v++;
            w--;
        }
        w++;
    }
    // check sulla tipologia poiche' ci sono oggetti che non hanno la tipologia tipo Opera e Parte
    if (typeClass != null) {
        String[] typeDefinitions = context.getBeanNamesForType(typeClass);
        int r = 0;
        int t = 0;
        for (String typeDefinition : typeDefinitions) {
            try {
                TY tipologiaDaImportare = (TY) context.getBean(typeDefinition);
                applicationService.saveOrUpdate(typeClass, tipologiaDaImportare);
            } catch (Exception ecc) {
                saveMessage(request, getText("action.file.nosuccess.metadato.upload",
                        new Object[] { ecc.getMessage() }, request.getLocale()));
                t++;
                r--;
            }
            r++;
        }

        saveMessage(request,
                getText("action.file.success.upload.tipologie",
                        new Object[] { new String("Totale Tipologie:" + (t + r) + " [" + r
                                + "caricate con successo/" + t + " fallito caricamento]") },
                        request.getLocale()));

    }

    saveMessage(request,
            getText("action.file.success.upload",
                    new Object[] {
                            new String("Totale TP:" + (i + j) + "" + "[" + i + " caricate con successo/" + j
                                    + " fallito caricamento]"),
                            new String("Totale Aree:" + (w + v) + " [" + w + "caricate con successo/" + v
                                    + " fallito caricamento]") },
                    request.getLocale()));

    return new ModelAndView(getDetailsView());
}

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

/**
 * ?/*from   www .ja  v a2  s. co m*/
 *
 * @param multipartFile
 * @param model
 * @return
 */
@RequestMapping(method = RequestMethod.POST)
public String upload(MultipartFile multipartFile, ModelMap model) {

    Member member = memberService.getCurrent();
    PhotosRequest request = new PhotosRequest();

    //getContentType()  = jpeg/image  png/image
    String type = multipartFile.getContentType().split("/")[1];

    String path = "/tmp/" + multipartFile.getName() + "_" + RandomStringUtils.randomNumeric(6) + "." + type;
    File destFile = new File(path);
    try {
        multipartFile.transferTo(destFile);
    } catch (IOException | IllegalStateException ex) {
        ex.printStackTrace();
    }
    //??(size)
    EasyImage easyImage = new EasyImage(path);

    request.setOrder(1);
    request.setMember(member);
    request.setWidth(easyImage.getWidth());
    request.setHeight(easyImage.getHeight());
    request.setSize(multipartFile.getSize());
    request.setTitle(multipartFile.getOriginalFilename());
    request.setSource(path);
    //        request.setDescription("?? ? setDescription");
    photosRequestService.create(request);

    return "/member/upload/result";
}

From source file:com.eryansky.core.web.upload.FileUploadUtils.java

/**
 * //from  ww w  .  j  a  v a  2 s. co  m
 *
 * @param request                   ? ??? 
 * @param dir                   request?,?;,??
 * @param file                      
 * @param allowedExtension          ? null ?
 * @param maxSize                   ? -1 ??
 * @param needDatePathAndRandomName ??????
 * @param _prefix ??? needDatePathAndRandomNamefalse
 * @return ???
 * @throws com.eryansky.core.web.upload.exception.InvalidExtensionException            MIME??
 * @throws org.apache.commons.fileupload.FileUploadBase.FileSizeLimitExceededException       ?
 * @throws com.eryansky.core.web.upload.exception.FileNameLengthLimitExceededException ??
 * @throws java.io.IOException                          
 */
public static final String upload(HttpServletRequest request, String dir, MultipartFile file,
        String[] allowedExtension, long maxSize, boolean needDatePathAndRandomName, String _prefix)
        throws InvalidExtensionException, FileSizeLimitExceededException, IOException,
        FileNameLengthLimitExceededException {

    int fileNamelength = file.getOriginalFilename().length();
    if (fileNamelength > FileUploadUtils.DEFAULT_FILE_NAME_LENGTH) {
        throw new FileNameLengthLimitExceededException(file.getOriginalFilename(), fileNamelength,
                FileUploadUtils.DEFAULT_FILE_NAME_LENGTH);
    }
    File desc = null;
    String filename = null;
    assertAllowed(file, allowedExtension, maxSize);
    if (request != null) {
        filename = extractFilename(file, dir, needDatePathAndRandomName, _prefix);
        desc = getAbsoluteFile(extractUploadDir(request), filename);
    } else {
        filename = extractFilename(file, dir, needDatePathAndRandomName, _prefix);
        String fileBasePath = getBasePath(filename);
        desc = getAbsoluteFile(fileBasePath);
    }

    file.transferTo(desc);
    return filename;
}

From source file:mvc.controller.UsuarioController.java

@RequestMapping(value = "/adicionaUsuario", method = RequestMethod.POST)
public String adiciona(HttpServletRequest request, Model model) {
    /*//w  w  w .j a  v  a2s . c om
    Configuracoes necessrias
    Fonte: http://www.pablocantero.com/blog/2010/09/29/upload-com-spring-mvc/
    */
    try {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        MultipartFile multipartFile = multipartRequest.getFile("photo");

        String destinyPath = "C:\\PhotosNetbeans\\";
        if (!(new File(destinyPath)).exists()) {
            (new File(destinyPath)).mkdir();
        }

        String photoName = multipartFile.getOriginalFilename();
        String photoPath = destinyPath + photoName;

        File photoFile = new File(photoPath);
        multipartFile.transferTo(photoFile);

        //backup
        //File destinationDir = new File(applicationPath);
        //FileUtils.copyFileToDirectory(photoFile, destinationDir);

        Usuario user = new Usuario();
        user.setLogin(request.getParameter("login"));
        user.setSenha(request.getParameter("senha"));
        user.setPhoto(photoPath);

        dao.adicionaUsuario(user);
        return "usuario/usuario-adicionado";

    } catch (IOException ex) {
        model.addAttribute("erro", ex.toString());
        return "usuario/usuario-erro-adicao";
    }
}

From source file:org.freeeed.search.files.CaseFileService.java

public String uploadFile(MultipartFile file) {
    File uploadDir = new File(UPLOAD_DIR);
    uploadDir.mkdirs();/*from   w w  w .j av a 2 s .c o m*/

    String destinationFile = UPLOAD_DIR + File.separator + df.format(new Date()) + "-"
            + file.getOriginalFilename();
    File destination = new File(destinationFile);
    try {
        file.transferTo(destination);

        return destinationFile;
    } catch (Exception e) {
        log.error("Problem uploading file: ", e);

        return null;
    }
}