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:cdr.forms.DepositFileEditor.java

public void setValue(Object value) {
    if (value instanceof MultipartFile) {
        MultipartFile multipartFile = (MultipartFile) value;

        if (multipartFile.getOriginalFilename().length() == 0) {
            super.setValue(null);
            return;
        }/* w  w  w.  j a v a2s .  co m*/

        try {
            File temp = File.createTempFile("temp", ".tmp");
            multipartFile.transferTo(temp);

            DepositFile depositFile = new DepositFile();
            depositFile.setFile(temp);
            depositFile.setFilename(multipartFile.getOriginalFilename());
            depositFile.setContentType(multipartFile.getContentType());
            depositFile.setSize(multipartFile.getSize());

            super.setValue(depositFile);
        } catch (IOException e) {
            throw new IllegalArgumentException(e);
        }
    } else if (value instanceof DepositFile) {
        super.setValue(value);
    } else {
        super.setValue(null);
    }
}

From source file:com.cami.web.controller.FileController.java

private void processFileData(MultipartFile file, String uploadDir, String nameOfFile)
        throws IllegalStateException, IOException {

    String filename = getSavedFileName(uploadDir, nameOfFile);
    file.transferTo(new File(filename));

}

From source file:onlinevideostore.controller.MovieController.java

@RequestMapping(value = "/addMovie", method = RequestMethod.POST)
public String addMovies(@Valid Movies movies, BindingResult result, Model model, HttpServletRequest request) {
    //javax.swing.JOptionPane.showMessageDialog(null, "hello");
    if (result.hasErrors()) {
        // javax.swing.JOptionPane.showMessageDialog(null, "hello2");

        return "addmovie";
    } else {/*w  w w  .  j av  a2  s. co m*/

        MultipartFile carImage = movies.getImage();
        //String rootDirectory = request.getSession().getServletContext().getRealPath("/");

        if (carImage != null && !carImage.isEmpty()) {
            try {
                carImage.transferTo(new File(saveDirectory + movies.getTitle() + ".png"));
            } catch (Exception e) {
                throw new RuntimeException("Product Image saving failed", e);
            }
        }

        movieService.addMovie(movies);
        // javax.swing.JOptionPane.showMessageDialog(null, movies.getTitle());
        model.addAttribute("movies", movies);
        return "movieDetail";
    }
}

From source file:no.dusken.aranea.admin.control.ImageUploadController.java

@RequestMapping(value = "/imageUpload/uploadFile.do", method = RequestMethod.POST)
public @ResponseBody String upload(@RequestParam MultipartFile file) throws IOException {
    File file1 = new File(workDir, file.getOriginalFilename());
    file.transferTo(file1);
    file1.deleteOnExit();//from w w w.j a v a 2s . c  o m
    return "SUCCESS";
}

From source file:com.carlos.projects.billing.ExcelToMySQLImporter.java

public Long importData(MultipartFile excelFile) throws ImportException {
    XSSFWorkbook workbook;/*  w  w  w.  jav a 2s .  c o m*/
    File componentsFile;
    try {
        componentsFile = new File("components-" + new Date().getTime() + ".xlsx");
        excelFile.transferTo(componentsFile);
        workbook = new XSSFWorkbook(componentsFile.getAbsolutePath());
    } catch (IOException e) {
        throw new ImportException(messages.getProperty("import.error"), e);
    }
    workbook.setMissingCellPolicy(Row.CREATE_NULL_AS_BLANK);
    Iterator<Row> rowIterator = workbook.getSheetAt(workbook.getActiveSheetIndex()).iterator();
    Long numberOfImportedItems = 0L;
    log.info("Starting reading from file " + excelFile.getOriginalFilename()
            + " to import components to database");
    while (rowIterator.hasNext()) {
        Row row = rowIterator.next();
        String familyCode = row.getCell(FAMILY_CODE).getStringCellValue().trim();
        //The first row of the excel file is the one with the titles
        if (row.getRowNum() != 0 && StringUtils.isNotBlank(familyCode)) {
            Family family = familyDAO.getById(Family.class, familyCode);
            boolean saveFamily = false;
            if (family == null) {
                family = createFamilyFromRow(row);
                saveFamily = true;
            }
            String componentCode = row.getCell(COMPONENT_CODE).getStringCellValue().trim();
            Component component = componentDAO.getById(Component.class, componentCode);
            boolean addComponent = false;
            if (component == null) {
                addComponent = true;
                component = createComponent(row, family);
                numberOfImportedItems += 1L;
            }
            if (saveFamily) {
                if (addComponent) {
                    family.addComponent(component);
                }
                familyDAO.save(family);
                log.info("Family " + family + " saved into the database");
            } else {
                componentDAO.save(component);
                log.info("Component " + component + " saved into the database");
            }
        }
    }
    closeAndDeleteTemporaryFiles(componentsFile);
    log.info("Components import to database finished");
    return numberOfImportedItems;
}

From source file:no.dusken.aranea.service.StoreImageServiceImpl.java

public Image changeImage(MultipartFile mFile, Image image) throws IOException {
    File file = new File(imageDirectory + "/tmp/" + mFile.getOriginalFilename());
    log.debug("creating file {}", file.getAbsolutePath());
    // ensure the needed directories are present:
    file.getParentFile().mkdirs();/*from  ww w  .j a  v a 2s  .  co  m*/
    mFile.transferTo(file);
    return changeImage(file, image);
}

From source file:org.openmrs.module.iqchartimport.web.controller.UploadController.java

@SuppressWarnings("unchecked")
@RequestMapping(method = RequestMethod.POST)
public String handleSubmit(HttpServletRequest request, ModelMap model) {
    Utils.checkSuperUser();//from w  ww  .  j a  va  2s.  c om

    DefaultMultipartHttpServletRequest multipart = (DefaultMultipartHttpServletRequest) request;
    MultipartFile uploadFile = multipart.getFile("mdbfile");

    IQChartDatabase.clearInstance();

    // Process uploaded database if there is one
    if (uploadFile != null) {
        try {
            // Copy uploaded MDB to temp file
            File tempMDBFile = File.createTempFile(uploadFile.getOriginalFilename(), ".temp");
            uploadFile.transferTo(tempMDBFile);

            // Store uploaded database as singleton
            IQChartDatabase.createInstance(uploadFile.getOriginalFilename(), tempMDBFile.getAbsolutePath());

        } catch (IOException e) {
            model.put("uploaderror", "Unable to upload database file");
        }
    }

    return showForm(request, model);
}

From source file:com.mycompany.rent.controllers.ListingController.java

@RequestMapping(value = "/savefiles", method = RequestMethod.POST)
public String crunchifySave(@ModelAttribute("uploadForm") UploadForm uploadForm)
        throws IllegalStateException, IOException {

    String saveDirectory = "/home/brennan/_repos/rent/src/main/webapp/uploads/";

    List<MultipartFile> crunchifyFiles = uploadForm.getFiles();

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

    ForRent fr = forRentDao.get(uploadForm.getProp_id());

    if (null != crunchifyFiles && crunchifyFiles.size() > 0) {
        for (MultipartFile multipartFile : crunchifyFiles) {

            String fileName = saveDirectory + uploadForm.getProp_id() + multipartFile.getOriginalFilename();
            if (!"".equalsIgnoreCase(fileName)) {
                // Handle file content - multipartFile.getInputStream()
                multipartFile.transferTo(new File(fileName));
                fileNames.add("/rent/uploads/" + uploadForm.getProp_id() + multipartFile.getOriginalFilename());
            }/*  w  w  w.  j ava2s  .  c o  m*/
        }
    }

    fr.setImagePaths(fileNames);

    //Iterate through ForRent imagePath and add each path to db
    for (String s : fr.getImagePaths()) {
        forRentDao.addPhotos(fr.getId(), s);
    }

    //        map.addAttribute("files", fileNames);
    return "pricing";
}

From source file:org.opencron.server.controller.TerminalController.java

@RequestMapping("/upload")
public void upload(HttpSession httpSession, HttpServletResponse response, String token,
        @RequestParam(value = "file", required = false) MultipartFile[] file, String path) {
    TerminalClient terminalClient = TerminalSession.get(token);
    boolean success = true;
    if (terminalClient != null) {
        for (MultipartFile ifile : file) {
            String tmpPath = httpSession.getServletContext().getRealPath("/") + "upload" + File.separator;
            File tempFile = new File(tmpPath, ifile.getOriginalFilename());
            try {
                ifile.transferTo(tempFile);
                if (CommonUtils.isEmpty(path)) {
                    path = ".";
                } else if (path.endsWith("/")) {
                    path = path.substring(0, path.lastIndexOf("/"));
                }//from w w  w . j a  va2  s  . co m
                terminalClient.upload(tempFile.getAbsolutePath(), path + "/" + ifile.getOriginalFilename(),
                        ifile.getSize());
                tempFile.delete();
            } catch (Exception e) {
                success = false;
            }
        }
    }
    WebUtils.writeJson(response, success ? "true" : "false");
}

From source file:org.shareok.data.dspacemanager.DspaceJournalDataUtil.java

/**
 * //from w w w  .  ja va 2s  .c  o m
 * @param file : the uploaded file
 * @param publisher : journal publisher, e.g. sage or plos
 * @return : the path of the uploading folder
 */
public static String saveUploadedData(MultipartFile file, String publisher) {
    String uploadedFilePath = null;
    try {
        String oldFileName = file.getOriginalFilename();
        String extension = DocumentProcessorUtil.getFileExtension(oldFileName);
        oldFileName = DocumentProcessorUtil.getFileNameWithoutExtension(oldFileName);
        //In the future the new file name will also has the user name
        String time = new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss").format(new Date());
        String newFileName = oldFileName + "--" + time + "." + extension;
        String uploadPath = getDspaceJournalUploadFolderPath(publisher);
        if (null != uploadPath) {
            File uploadFolder = new File(uploadPath);
            if (!uploadFolder.exists()) {
                uploadFolder.mkdir();
            }
            File uploadTimeFolder = new File(uploadPath + File.separator + time);
            if (!uploadTimeFolder.exists()) {
                uploadTimeFolder.mkdir();
            }
        }
        uploadedFilePath = uploadPath + File.separator + time + File.separator + newFileName;
        File uploadedFile = new File(uploadedFilePath);
        file.transferTo(uploadedFile);
    } catch (Exception ex) {
        Logger.getLogger(DspaceJournalDataUtil.class.getName()).log(Level.SEVERE, null, ex);
    }
    return uploadedFilePath;
}