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:org.springframework.batch.admin.web.FileController.java

@RequestMapping(value = "/files/{path}", method = RequestMethod.POST)
public String upload(@PathVariable String path, @RequestParam MultipartFile file, ModelMap model,
        @RequestParam(defaultValue = "0") int startFile, @RequestParam(defaultValue = "20") int pageSize,
        @ModelAttribute("date") Date date, Errors errors) throws Exception {

    String originalFilename = file.getOriginalFilename();
    if (file.isEmpty()) {
        errors.reject("file.upload.empty", new Object[] { originalFilename },
                "File upload was empty for filename=[" + HtmlUtils.htmlEscape(originalFilename) + "]");
        list(model, startFile, pageSize);
        return "files";
    }//from w w  w .j ava 2s . co m

    try {
        FileInfo dest = fileService.createFile(path + "/" + originalFilename);
        file.transferTo(fileService.getResource(dest.getPath()).getFile());
        fileService.publish(dest);
        model.put("uploaded", dest.getPath());
    } catch (IOException e) {
        errors.reject("file.upload.failed", new Object[] { originalFilename },
                "File upload failed for " + HtmlUtils.htmlEscape(originalFilename));
    } catch (Exception e) {
        String message = "File upload failed downstream processing for "
                + HtmlUtils.htmlEscape(originalFilename);
        if (logger.isDebugEnabled()) {
            logger.debug(message, e);
        } else {
            logger.info(message);
        }
        errors.reject("file.upload.failed.downstream", new Object[] { originalFilename }, message);
    }

    if (errors.hasErrors()) {
        list(model, startFile, pageSize);
        return "files";
    }

    return "redirect:files";

}

From source file:org.springframework.data.hadoop.admin.web.TemplateController.java

@RequestMapping(value = "/templates/{path}", method = RequestMethod.POST)
public String upload(@PathVariable String path, @RequestParam MultipartFile file, ModelMap model,
        @RequestParam(defaultValue = "0") int startFile, @RequestParam(defaultValue = "20") int pageSize,
        @ModelAttribute("date") Date date, Errors errors) throws Exception {

    String originalFilename = file.getOriginalFilename();
    if (file.isEmpty()) {
        errors.reject("file.upload.empty", new Object[] { originalFilename },
                "File upload was empty for filename=[" + HtmlUtils.htmlEscape(originalFilename) + "]");
        list(model, startFile, pageSize);
        return "workflows";
    }//from w  w  w  . jav a2  s.  co m

    try {
        FileInfo dest = templateService.createFile(path + "/" + originalFilename);
        file.transferTo(templateService.getResource(dest.getPath()).getFile());
        templateService.publish(dest);
        model.put("uploaded", dest.getPath());
    } catch (IOException e) {
        errors.reject("file.upload.failed", new Object[] { originalFilename },
                "File upload failed for " + HtmlUtils.htmlEscape(originalFilename));
    } catch (Exception e) {
        String message = "File upload failed downstream processing for "
                + HtmlUtils.htmlEscape(originalFilename);
        if (logger.isDebugEnabled()) {
            logger.debug(message, e);
        } else {
            logger.info(message);
        }
        errors.reject("file.upload.failed.downstream", new Object[] { originalFilename }, message);
    }

    if (errors.hasErrors()) {
        list(model, startFile, pageSize);
        return "templates";
    }

    return "redirect:templates";

}

From source file:org.springframework.data.hadoop.admin.web.WorkflowController.java

@RequestMapping(value = "/workflows/{path}", method = RequestMethod.POST)
public String upload(@PathVariable String path, @RequestParam MultipartFile file, ModelMap model,
        @RequestParam(defaultValue = "0") int startFile, @RequestParam(defaultValue = "20") int pageSize,
        @ModelAttribute("date") Date date, Errors errors) throws Exception {

    String originalFilename = file.getOriginalFilename();
    if (file.isEmpty()) {
        errors.reject("file.upload.empty", new Object[] { originalFilename },
                "File upload was empty for filename=[" + HtmlUtils.htmlEscape(originalFilename) + "]");
        list(model, startFile, pageSize);
        return "workflows";
    }/*w  w w.j av  a2s  .c om*/

    try {
        FileInfo dest = workflowService.createFile(path + "/" + originalFilename);
        file.transferTo(workflowService.getResource(dest.getPath()).getFile());
        workflowService.publish(dest);
        model.put("uploaded", dest.getPath());
    } catch (IOException e) {
        errors.reject("file.upload.failed", new Object[] { originalFilename },
                "File upload failed for " + HtmlUtils.htmlEscape(originalFilename));
    } catch (Exception e) {
        String message = "File upload failed downstream processing for "
                + HtmlUtils.htmlEscape(originalFilename);
        if (logger.isDebugEnabled()) {
            logger.debug(message, e);
        } else {
            logger.info(message);
        }
        errors.reject("file.upload.failed.downstream", new Object[] { originalFilename }, message);
    }

    if (errors.hasErrors()) {
        list(model, startFile, pageSize);
        return "workflows";
    }

    return "redirect:workflows";

}

From source file:org.springframework.integration.http.DefaultInboundRequestMapper.java

@SuppressWarnings("unchecked")
private Object createPayloadFromMultipartRequest(MultipartHttpServletRequest multipartRequest) {
    Map<String, Object> payloadMap = new HashMap<String, Object>(multipartRequest.getParameterMap());
    Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
    for (Map.Entry<String, MultipartFile> entry : fileMap.entrySet()) {
        MultipartFile multipartFile = entry.getValue();
        if (multipartFile.isEmpty()) {
            continue;
        }//from  w ww  . j  a v  a  2 s.  co m
        try {
            if (this.copyUploadedFiles) {
                File tmpFile = File.createTempFile("si_", null);
                multipartFile.transferTo(tmpFile);
                payloadMap.put(entry.getKey(), tmpFile);
                if (logger.isDebugEnabled()) {
                    logger.debug("copied uploaded file [" + multipartFile.getOriginalFilename()
                            + "] to temporary file [" + tmpFile.getAbsolutePath() + "]");
                }
            } else if (multipartFile.getContentType() != null
                    && multipartFile.getContentType().startsWith("text")) {
                String multipartFileAsString = this.multipartCharset != null
                        ? new String(multipartFile.getBytes(), this.multipartCharset)
                        : new String(multipartFile.getBytes());
                payloadMap.put(entry.getKey(), multipartFileAsString);
            } else {
                payloadMap.put(entry.getKey(), multipartFile.getBytes());
            }
        } catch (IOException e) {
            throw new IllegalArgumentException("Cannot read contents of multipart file", e);
        }
    }
    return Collections.unmodifiableMap(payloadMap);
}

From source file:org.springframework.integration.http.FileCopyingMultipartFileReader.java

public MultipartFile readMultipartFile(MultipartFile multipartFile) throws IOException {
    File upload = File.createTempFile(this.prefix, this.suffix, this.directory);
    multipartFile.transferTo(upload);
    UploadedMultipartFile uploadedMultipartFile = new UploadedMultipartFile(upload, multipartFile.getSize(),
            multipartFile.getContentType(), multipartFile.getName(), multipartFile.getOriginalFilename());
    if (logger.isDebugEnabled()) {
        logger.debug("copied uploaded file [" + multipartFile.getOriginalFilename() + "] to ["
                + upload.getAbsolutePath() + "]");
    }//www  .j ava 2 s  .  c o  m
    return uploadedMultipartFile;
}

From source file:org.vpac.web.controller.DataController.java

@RequestMapping(value = "/Upload", method = RequestMethod.POST)
//public String uploadFile(@RequestParam String timeSliceId, @RequestParam MultipartFile file, @RequestParam(required = false) String fileId, @RequestParam(required = false) String count, ModelMap model) throws IOException {
public String uploadFile(@Valid FileRequest fileRequest, ModelMap model) throws Exception {

    log.info("File Upload");
    log.debug("Timeslice ID: {}", fileRequest.getTimeSliceId());
    log.debug("Task ID: {}", fileRequest.getTaskId());

    Upload upload;/*from www  . j ava 2s  .  co m*/
    if (fileRequest.getTaskId() == null || fileRequest.getTaskId().isEmpty()) {
        upload = new Upload(fileRequest.getTimeSliceId());
        uploadDao.create(upload);
        log.debug("Create UploadFileId: {}", upload.getFileId());
    } else {
        upload = uploadDao.retrieve(fileRequest.getTaskId());
        if (upload == null) {
            // Capture if band not exist
            throw new ResourceNotFoundException(
                    String.format("Upload with task ID = \"%s\" not found.", fileRequest.getTaskId()));
        }
        log.debug("Retrieve UploadFileId: {}", upload.getFileId());
    }
    Path fileIdDir = uploadUtil.getDirectory(upload).toAbsolutePath();
    uploadUtil.createDirectory(upload);

    for (MultipartFile file : fileRequest.getFiles()) {
        Path target = fileIdDir.resolve(file.getOriginalFilename());
        if (!file.isEmpty())
            file.transferTo(target.toFile());
    }

    model.addAttribute(ControllerHelper.RESPONSE_ROOT, new FileInfoResponse(upload.getFileId()));
    return "FileUploadSuccess";
}

From source file:ru.org.linux.spring.AddMessageForm.java

public AddMessageForm(HttpServletRequest request, Template tmpl)
        throws IOException, ScriptErrorException, ServletRequestBindingException {
    postIP = request.getRemoteAddr();// www . ja v  a 2  s  .  c  om

    noinfo = "1".equals(request.getParameter("noinfo"));
    sessionId = request.getParameter("session");
    preview = request.getParameter("preview") != null;
    if (!"GET".equals(request.getMethod())) {
        captchaResponse = request.getParameter("j_captcha_response");
        nick = request.getParameter("nick");
        password = request.getParameter("password");
        mode = request.getParameter("mode");
        title = request.getParameter("title");
        msg = request.getParameter("msg");
    }

    if (request.getParameter("group") == null) {
        throw new ScriptErrorException("missing group parameter");
    }

    guid = ServletRequestUtils.getRequiredIntParameter(request, "group");

    linktext = request.getParameter("linktext");
    url = request.getParameter("url");
    returnUrl = request.getParameter("return");
    tags = request.getParameter("tags");

    if (request instanceof MultipartHttpServletRequest) {
        MultipartFile multipartFile = ((MultipartRequest) request).getFile("image");
        if (multipartFile != null && !multipartFile.isEmpty()) {
            File uploadedFile = File.createTempFile("preview", "",
                    new File(tmpl.getObjectConfig().getPathPrefix() + "/linux-storage/tmp/"));
            image = uploadedFile.getPath();
            if ((uploadedFile.canWrite() || uploadedFile.createNewFile())) {
                try {
                    logger.debug("Transfering upload to: " + image);
                    multipartFile.transferTo(uploadedFile);
                } catch (Exception e) {
                    throw new ScriptErrorException("Failed to write uploaded file", e);
                }
            } else {
                logger.info("Bad target file name: " + image);
            }
        }
    }

    List<String> pollList = new ArrayList<String>();

    for (int i = 0; i < Poll.MAX_POLL_SIZE; i++) {
        String poll = request.getParameter("var" + i);

        if (poll != null) {
            pollList.add(poll);
        }
    }

    if (pollList.isEmpty()) {
        this.pollList = null;
    } else {
        this.pollList = ImmutableList.copyOf(pollList);
    }

    if (request.getParameter("multiSelect") != null) {
        multiSelect = true;
    }
}

From source file:ru.org.linux.user.AddPhotoController.java

@RequestMapping(value = "/addphoto.jsp", method = RequestMethod.POST)
@PreAuthorize("hasRole('ROLE_ANONYMOUS')")
public ModelAndView addPhoto(@RequestParam("file") MultipartFile file, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    if (file == null || file.isEmpty()) {
        return new ModelAndView("addphoto", "error", "  ");
    }/*from  w  w w. j av  a  2s. c  o  m*/

    try {
        File uploadedFile = File.createTempFile("userpic", "",
                new File(configuration.getPathPrefix() + "/linux-storage/tmp/"));

        file.transferTo(uploadedFile);

        UserService.checkUserpic(uploadedFile);
        String extension = ImageInfo.detectImageType(uploadedFile);

        Random random = new Random();

        String photoname;
        File photofile;

        do {
            photoname = Integer.toString(AuthUtil.getCurrentUser().getId()) + ':' + random.nextInt() + '.'
                    + extension;
            photofile = new File(configuration.getHTMLPathPrefix() + "/photos", photoname);
        } while (photofile.exists());

        if (!uploadedFile.renameTo(photofile)) {
            logger.warn("Can't move photo to " + photofile);
            throw new ScriptErrorException("Can't move photo: internal error");
        }

        userDao.setPhoto(AuthUtil.getCurrentUser(), photoname);

        logger.info("? ?  "
                + AuthUtil.getCurrentUser().getNick());

        return new ModelAndView(new RedirectView(UriComponentsBuilder
                .fromUri(PROFILE_NOCACHE_URI_TEMPLATE.expand(AuthUtil.getCurrentUser().getNick()))
                .queryParam("nocache", Integer.toString(random.nextInt()) + "=").build().encode().toString()));
    } catch (IOException ex) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return new ModelAndView("addphoto", "error", ex.getMessage());
    } catch (BadImageException ex) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return new ModelAndView("addphoto", "error", ex.getMessage());
    } catch (UserErrorException ex) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return new ModelAndView("addphoto", "error", ex.getMessage());
    }
}

From source file:won.owner.web.rest.RestNeedPhotoController.java

@ResponseBody
@RequestMapping(value = "/", method = RequestMethod.POST)
public ResponseEntity uploadPhoto(@RequestParam("photo") MultipartFile photo,
        @RequestParam("unique") String uniqueKey, @RequestParam("selected") String selected) {
    File tempDir = new File(uniqueKey);
    if (!tempDir.exists())
        tempDir.mkdir();/*  w  ww.j  av  a 2  s  .co m*/
    File photoTempFile = new File(tempDir,
            selected + "." + FilenameUtils.getExtension(photo.getOriginalFilename()));
    try {
        logger.info("Saving file to " + photoTempFile.getAbsolutePath());
        photo.transferTo(photoTempFile);
        return new ResponseEntity(HttpStatus.OK);
    } catch (IOException e) {
        return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR);
        //log.error("An error occurred.", e);
    }
}