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.askme.controller.app.AppController.java

@RequestMapping(value = "/user/changeProfile", method = RequestMethod.POST)
public String postChangeProfile(@Valid User user, BindingResult result, ModelMap model,
        RedirectAttributes redirect, HttpServletRequest request,
        @RequestParam(value = "file", required = false) MultipartFile file) {
    passwordValidator.validate(user, result);
    if (result.hasErrors()) {
        System.out.println(result.getAllErrors());
        return "change_profile";
    }//from w  ww.j a  v  a  2  s . com

    // Upload avatar
    if (file != null) {
        try {
            InputStream inputStream = file.getInputStream();
            if (inputStream == null) {
                System.out.println("File inputstream is null");
            }
            String path = request.getServletContext().getRealPath("/") + "public/avatar/";
            FileUtils.forceMkdir(new File(path));
            File upload = new File(path + file.getOriginalFilename());
            file.transferTo(upload);
            user.setAvatar(file.getOriginalFilename());
            IOUtils.closeQuietly(inputStream);
        } catch (IOException ex) {
            System.out.println("Error saving uploaded file");
        }
    }

    userService.update(user);

    redirect.addFlashAttribute("success", "Cp nht profile thnh cng");
    return "redirect:/login";
}

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

@Override
public String savePayvoucher(HttpServletRequest request, String user_id, int main_id,
        JpaAttachment.Type file_type, String description) throws BusinessException {
    String result = "";
    try {/*from  w w  w .  j a  v a  2s .com*/
        CustomMultipartResolver multipartResolver = new CustomMultipartResolver(
                request.getSession().getServletContext());
        log.info("userid:{},main_id:{},file_type:{}", user_id, main_id, file_type);
        if (multipartResolver.isMultipart(request)) {
            String path = request.getSession().getServletContext()
                    .getRealPath(com.pantuo.util.Constants.FILE_UPLOAD_DIR).replaceAll("WEB-INF", "");
            log.info("path=", path);
            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();
                    String fn = file.getName();
                    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);
                        AttachmentExample example = new AttachmentExample();
                        AttachmentExample.Criteria criteria = example.createCriteria();
                        criteria.andMainIdEqualTo(main_id);
                        criteria.andUserIdEqualTo(user_id);
                        criteria.andTypeEqualTo(JpaAttachment.Type.payvoucher.ordinal());
                        List<Attachment> attachments = attachmentMapper.selectByExample(example);
                        if (attachments.size() > 0) {
                            Attachment t = attachments.get(0);
                            t.setUpdated(new Date());
                            t.setName(oriFileName);
                            t.setUrl(p.getRight());
                            attachmentMapper.updateByPrimaryKey(t);
                            result = p.getRight();
                        } else {
                            Attachment t = new Attachment();
                            if (StringUtils.isNotBlank(description)) {
                                t.setDescription(description);
                            }
                            t.setMainId(main_id);
                            t.setType(file_type.ordinal());
                            t.setCreated(new Date());
                            t.setUpdated(t.getCreated());
                            t.setName(oriFileName);
                            t.setUrl(p.getRight());
                            t.setUserId(user_id);
                            attachmentMapper.insert(t);
                            result = p.getRight();
                        }
                    }
                }
            }
        }

    } catch (Exception e) {
        log.error("saveAttachment", e);
        throw new BusinessException("saveAttachment-error", e);
    }
    return result;
}

From source file:com.tssa.cooperationBusiness.controller.CooperationController.java

public String saveFile(HttpServletRequest request) {
    String filePath = "";
    try {/*from   w  ww. jav a 2 s.co m*/
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        MultipartFile multiFile = multipartRequest.getFile("businessLicensePic");
        String fileUrl = request.getServletContext().getRealPath("/") + "upload/";
        String viewUrl = request.getServletContext().getContextPath() + "/upload/";
        // 
        //         String fileUrl = "/Users/gmc/Works/eclipse/workspace/TSSA/WebContent/WEB-INF/upload/";

        File file = new File(fileUrl);
        if (!file.exists()) {
            file.mkdirs();
        }

        if (multiFile != null
                && (multiFile.getOriginalFilename() != null && !"".equals(multiFile.getOriginalFilename()))) {
            File uploadFile = new File(fileUrl + multiFile.getOriginalFilename());
            multiFile.transferTo(uploadFile);

            filePath = viewUrl + multiFile.getOriginalFilename();

            return filePath;

        } else {
            return null;
        }
    } catch (IOException e) {
        LOG.error(e.getMessage(), e);
    }
    return filePath;
}

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

public void saveAttachment(HttpServletRequest request, String user_id, int main_id,
        JpaAttachment.Type file_type, String description) throws BusinessException {

    try {/*from w  w  w . ja v  a2  s  .c  o  m*/
        CustomMultipartResolver multipartResolver = new CustomMultipartResolver(
                request.getSession().getServletContext());
        log.info("userid:{},main_id:{},file_type:{}", user_id, main_id, file_type);
        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();
                    String fn = file.getName();
                    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);
                        AttachmentExample example = new AttachmentExample();
                        AttachmentExample.Criteria criteria = example.createCriteria();
                        criteria.andMainIdEqualTo(main_id);
                        criteria.andUserIdEqualTo(user_id);
                        criteria.andTypeEqualTo(JpaAttachment.Type.user_qualifi.ordinal());
                        List<Attachment> attachments = attachmentMapper.selectByExample(example);
                        if (attachments.size() > 0) {
                            Attachment t = attachments.get(0);
                            t.setUpdated(new Date());
                            t.setName(oriFileName);
                            t.setUrl(p.getRight());
                            attachmentMapper.updateByPrimaryKey(t);

                        } else {
                            Attachment t = new Attachment();
                            if (StringUtils.isNotBlank(description)) {
                                t.setDescription(description);
                            }
                            t.setMainId(main_id);
                            if (StringUtils.equals(fn, "licensefile")) {
                                t.setType(JpaAttachment.Type.license.ordinal());
                            } else if (fn.indexOf("qua") != -1) {
                                t.setType(JpaAttachment.Type.u_fj.ordinal());
                            } else if (StringUtils.equals(fn, "taxfile")) {
                                t.setType(JpaAttachment.Type.tax.ordinal());
                            } else if (StringUtils.equals(fn, "taxpayerfile")) {
                                t.setType(JpaAttachment.Type.taxpayer.ordinal());
                            } else if (StringUtils.equals(fn, "user_license")) {
                                t.setType(JpaAttachment.Type.user_license.ordinal());
                            } else if (StringUtils.equals(fn, "user_code")) {
                                t.setType(JpaAttachment.Type.user_code.ordinal());
                            } else if (StringUtils.equals(fn, "user_tax")) {
                                t.setType(JpaAttachment.Type.user_tax.ordinal());
                            } else {
                                t.setType(file_type.ordinal());
                            }
                            t.setCreated(new Date());
                            t.setUpdated(t.getCreated());
                            t.setName(oriFileName);
                            t.setUrl(p.getRight());
                            t.setUserId(user_id);
                            attachmentMapper.insert(t);
                        }
                    }
                }
            }
        }

    } catch (Exception e) {
        log.error("saveAttachment", e);
        throw new BusinessException("saveAttachment-error", e);
    }

}

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

@RequestMapping("/config/{id}/files")
@ResponseBody//from   ww  w.j a  va 2 s. co  m
public Map<String, String> uploadFiles(@PathVariable String id, @RequestParam String keterangan,
        @RequestParam MultipartFile cv, @RequestParam MultipartFile foto) throws Exception {
    ApplicationConfig config = belajarRestfulService.findApplicationConfigById(id);
    if (config == null) {
        throw new IllegalStateException();
    }

    Map<String, String> result = new HashMap<String, String>();

    logger.info("CV => Content-Type : {}, Filename : {}, Size : {}",
            new Object[] { cv.getContentType(), cv.getOriginalFilename(), cv.getSize() });

    logger.info("Foto => Content-Type : {}, Filename : {}, Size : {}",
            new Object[] { foto.getContentType(), foto.getOriginalFilename(), foto.getSize() });

    File cvTarget = File.createTempFile(cv.getOriginalFilename().split(ESC_CHAR_TITIK)[0],
            "." + cv.getOriginalFilename().split(ESC_CHAR_TITIK)[1]);
    File fotoTarget = File.createTempFile(foto.getOriginalFilename().split(ESC_CHAR_TITIK)[0],
            "." + foto.getOriginalFilename().split(ESC_CHAR_TITIK)[1]);
    cv.transferTo(cvTarget);
    foto.transferTo(fotoTarget);

    logger.info("CV disimpan ke {}", cvTarget.getAbsolutePath());
    logger.info("Foto disimpan ke {}", fotoTarget.getAbsolutePath());

    if (cv.getSize() == UKURAN_FILE_CV) {
        result.put("cv", "success");
    } else {
        result.put("cv", "error size");
    }

    if (foto.getSize() == UKURAN_FILE_FOTO) {
        result.put("foto", "success");
    } else {
        result.put("foto", "error size");
    }

    if ("File Endy".equals(keterangan)) {
        result.put("keterangan", "success");
    } else {
        result.put("keterangan", "salah content");
    }

    return result;
}

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

public void updateAttachments(HttpServletRequest request, String user_id, int main_id,
        JpaAttachment.Type file_type, String description) throws BusinessException {

    try {/*from  w  w  w. j  a va 2  s  .co 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();
                    String fn = file.getName();
                    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);
                        AttachmentExample example = new AttachmentExample();
                        AttachmentExample.Criteria criteria = example.createCriteria();
                        criteria.andMainIdEqualTo(main_id);
                        criteria.andUserIdEqualTo(user_id);
                        List<Attachment> attachments = attachmentMapper.selectByExample(example);
                        for (Attachment t : attachments) {
                            if (StringUtils.equals(fn, "licensefile")
                                    && t.getType() == JpaAttachment.Type.license.ordinal()) {
                                t.setUpdated(new Date());
                                t.setName(oriFileName);
                                t.setUrl(p.getRight());
                                attachmentMapper.updateByPrimaryKey(t);
                            }
                            if (StringUtils.equals(fn, "taxfile")
                                    && t.getType() == JpaAttachment.Type.tax.ordinal()) {
                                t.setUpdated(new Date());
                                t.setName(oriFileName);
                                t.setUrl(p.getRight());
                                attachmentMapper.updateByPrimaryKey(t);
                            }
                            if (StringUtils.equals(fn, "taxpayerfile")
                                    && t.getType() == JpaAttachment.Type.taxpayer.ordinal()) {
                                t.setUpdated(new Date());
                                t.setName(oriFileName);
                                t.setUrl(p.getRight());
                                attachmentMapper.updateByPrimaryKey(t);
                            }
                            if (StringUtils.equals(fn, "user_license")
                                    && t.getType() == JpaAttachment.Type.user_license.ordinal()) {
                                t.setUpdated(new Date());
                                t.setName(oriFileName);
                                t.setUrl(p.getRight());
                                attachmentMapper.updateByPrimaryKey(t);
                            }
                            if (StringUtils.equals(fn, "user_tax")
                                    && t.getType() == JpaAttachment.Type.user_tax.ordinal()) {
                                t.setUpdated(new Date());
                                t.setName(oriFileName);
                                t.setUrl(p.getRight());
                                attachmentMapper.updateByPrimaryKey(t);
                            }
                            if (StringUtils.equals(fn, "user_code")
                                    && t.getType() == JpaAttachment.Type.user_code.ordinal()) {
                                t.setUpdated(new Date());
                                t.setName(oriFileName);
                                t.setUrl(p.getRight());
                                attachmentMapper.updateByPrimaryKey(t);
                            }

                        }
                    }
                }
            }
        }

    } catch (Exception e) {
        log.error("saveAttachment", e);
        throw new BusinessException("saveAttachment-error", e);
    }
}

From source file:de.zib.gndms.dspace.service.SliceServiceImpl.java

@RequestMapping(value = "/_{subspace}/_{sliceKind}/_{sliceId}/files", method = RequestMethod.POST)
@Secured("ROLE_USER")
public ResponseEntity<Integer> setFileContents(@PathVariable final String subspaceId,
        @PathVariable final String sliceKind, @PathVariable final String sliceId,
        @RequestParam("files") final List<MultipartFile> files, @RequestHeader("DN") final String dn) {
    GNDMSResponseHeader headers = setHeaders(subspaceId, sliceKind, sliceId, dn);

    try {//from   w w  w .j a  v a  2 s  .c  o  m
        Subspace space = subspaceProvider.get(subspaceId);
        Slice slice = findSliceOfKind(subspaceId, sliceKind, sliceId);
        String path = space.getPathForSlice(slice);

        final long sliceMaxSize = slice.getTotalStorageSize();

        for (MultipartFile file : files) {
            long sliceSize = sliceProvider.getDiskUsage(subspaceId, sliceId);
            if (sliceSize >= sliceMaxSize)
                throw new IOException(
                        "Slice " + sliceId + " has reached maximum size of " + sliceMaxSize + " Bytes");

            File newFile = new File(path + File.separatorChar + file.getOriginalFilename());

            if (newFile.exists()) {
                logger.warn("File " + newFile + "will be overwritten.");
            }

            file.transferTo(newFile);
        }
        return new ResponseEntity<Integer>(0, headers, HttpStatus.OK);
    } catch (NoSuchElementException ne) {
        logger.warn(ne.getMessage(), ne);
        return new ResponseEntity<Integer>(0, headers, HttpStatus.NOT_FOUND);
    } catch (FileNotFoundException e) {
        logger.warn(e.getMessage(), e);
        return new ResponseEntity<Integer>(0, headers, HttpStatus.FORBIDDEN);
    } catch (IOException e) {
        logger.warn(e.getMessage(), e);
        return new ResponseEntity<Integer>(0, headers, HttpStatus.FORBIDDEN);
    }
}

From source file:cn.mk.ndms.modules.lease.web.controller.LeaseController.java

@RequestMapping(value = "upload", method = RequestMethod.POST)
@ResponseBody//from  w w  w . ja  v a  2  s  .  c om
public AjaxBean upload(HttpServletRequest request, HttpServletResponse response) throws IOException {
    try {
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
                request.getSession().getServletContext());
        if (multipartResolver.isMultipart(request)) {
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
            Iterator<String> iter = multiRequest.getFileNames();
            while (iter.hasNext()) {
                MultipartFile file = multiRequest.getFile((String) iter.next());
                if (file != null) {
                    String fileName = file.getOriginalFilename();
                    String path1 = Thread.currentThread().getContextClassLoader().getResource("").getPath()
                            + "file" + File.separator;
                    //  ???
                    String path2 = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + fileName;
                    String path = path1 + path2;
                    File localFile = new File(path);
                    file.transferTo(localFile);
                    Lease lease = leaseService.findOne(request.getParameter("id"));
                    lease.setFilePath(path2);
                    leaseService.update(lease);
                }
            }
        }
        return AjaxBean.getInstance("success");
    } catch (Exception ex) {
        return AjaxBean.getInstance("error", ex.getMessage());
    }
}

From source file:ru.codemine.ccms.router.TaskRouter.java

@Secured("ROLE_USER")
@RequestMapping(value = "/tasks/addfile", method = RequestMethod.POST)
public String addFileToTask(@RequestParam("file") MultipartFile file, @RequestParam("id") Integer id) {
    Task task = taskService.getById(id);
    Employee employee = employeeService.getCurrentUser();

    if (file.isEmpty())
        return "redirect:/tasks/taskinfo?id=" + task.getId();

    if (employee.equals(task.getCreator()) || task.getPerformers().contains(employee)) {
        String filename = settingsService.getStorageTasksPath() + UUID.randomUUID().toString();
        String viewname = file.getOriginalFilename();
        File targetFile = new File(filename);

        DataFile targetDataFile = new DataFile(employee);
        targetDataFile.setFilename(filename);
        targetDataFile.setViewName(viewname);
        targetDataFile.setSize(file.getSize());
        targetDataFile.setTypeByExtension();

        try {/*from   w ww . j  ava 2s  .c  om*/
            file.transferTo(targetFile);
        } catch (IOException | IllegalStateException ex) {
            log.error("    " + viewname + ", : "
                    + ex.getLocalizedMessage());
            return "redirect:/tasks/taskinfo?id=" + task.getId();
        }

        dataFileService.create(targetDataFile);
        task.getFiles().add(targetDataFile);
        taskService.update(task);
    }

    return "redirect:/tasks/taskinfo?id=" + task.getId();
}

From source file:com.pkrete.locationservice.admin.service.illustrations.ImagesServiceImpl.java

/**
 * Adds the given image object to the database and to the file system.
 *
 * @param image the image to be added/*from   w w w.j  a v a 2s  . c  o  m*/
 * @return true if and only if the image was successfully added; otherwise
 * false
 */
@Override
public boolean create(Image image) {
    // Set created date
    image.setCreated(new Date());
    // Get path of the images dir
    String path = Settings.getInstance().getImagesPath(image.getOwner().getCode());
    // Get path of the images admin dir
    String adminPath = Settings.getInstance().getImagesPathAdmin(image.getOwner().getCode());

    if (image.getFilePath() != null && image.getFilePath().length() > 0) {
        logger.debug("Move uploaded image file from admin dir to service dir.");
        // Image is moved from admin dir to service dir.
        // FilePath variable contains the name of the image file
        String name = image.getFilePath();
        // Name must be unique
        name = this.getUniqueName(path, name);
        // Path variable must be updated
        image.setPath(name);
        // The image is not external
        image.setIsExternal(false);
        // Absolute target path
        path += image.getPath();
        // Absolute source path
        adminPath += image.getFilePath();
        // Check that the file really exists
        if (!this.adminImageExists(image.getFilePath(), image.getOwner())) {
            logger.warn("Creating image failed, because the given file doesn't exist! Path : {}", adminPath);
            return false;
        }
        logger.info("Move image file : \"{}\" -> \"{}\"", adminPath, path);
        // Try to rename (=move) the file
        if (!fileService.rename(adminPath, path)) {
            logger.warn("Moving image file failed! Creating new image failed!");
            return false;
        }
    } else if (image.getUrl() != null && image.getUrl().length() > 0) {
        // Set path
        image.setPath(image.getUrl());
        // Image is external
        image.setIsExternal(true);
    } else if (image.getFile() != null && image.getFile().getSize() > 0) {
        logger.debug("Add uploaded image file.");
        // User has uploaded a file
        MultipartFile file = image.getFile();
        // Get the name of the file
        String name = file.getOriginalFilename();
        // Name must be unique
        name = this.getUniqueName(path, name);
        // Update path variable
        image.setPath(name);
        // Absolute target path
        path += image.getPath();
        // Image is not external
        image.setIsExternal(false);
        // Create a new File object for the uploaded file
        File imageFile = new File(path);

        logger.info("Write uploaded image file to disk. Path : \"{}\"", path);

        try {
            // Write the uploaded file to disk
            file.transferTo(imageFile);
        } catch (IOException ex) {
            logger.warn("Writing image file to disk failed! Creating image failed!");
            logger.error(ex.getMessage(), ex);
            return false;
        }
        // Check that the file really exists
        if (!fileService.exists(path)) {
            logger.warn("Writing image file to disk failed! File doesn't exist. Path : \"{}\"", path);
            return false;
        }
    }
    // Try to save the image to DB
    if (dao.create(image)) {
        logger.info("Image created : {}", this.jsonizer.jsonize(image, true));
        return true;
    }
    logger.warn("Failed to create image : {}", this.jsonizer.jsonize(image, true));
    return false;
}