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.chimi.s4s.controller.FileUploadController.java

private File getTemporaryFile(MultipartFile userUploadFile) throws IllegalStateException, IOException {
    StringBuilder tempNameBuilder = new StringBuilder();
    tempNameBuilder.append(System.currentTimeMillis()).append(".").append(random.nextInt(1000));
    File tempFile = new File(Util.getS4STempDir(), tempNameBuilder.toString());
    userUploadFile.transferTo(tempFile);
    return tempFile;
}

From source file:no.dusken.aranea.admin.control.issue.EditIssueController.java

@Override
protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object o,
        BindException e) throws Exception {
    Issue issue = (Issue) o;/*from   w w w .  j ava  2  s  .c  o  m*/

    MultipartHttpServletRequest mrequest = (MultipartHttpServletRequest) request;
    MultipartFile file = mrequest.getFile("file");
    if (file != null && !file.isEmpty()) {
        issue.setPdfSize(file.getSize());
        String pdfUrl = pdfDirectory + issue.getRelativePdfFilePath();
        // transfer the pdf
        File destFile = new File(pdfUrl);
        destFile.getParentFile().mkdirs();
        file.transferTo(destFile);

        issue.clearPdfPages();
        issueIndexer.tryToIndexIssue(issue);

        try {
            Image image = imageUtils.makeThumbnail(destFile);
            issue.setImage(image);
        } catch (Exception ex) {
            log.error("Error when creating pdf image");
        }
    }
    MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
    MultipartFile image = multipartRequest.getFile("img");
    if (image != null && image.getSize() != 0) {
        Image i = storeImageService.createImage(image);
        issue.setImage(i);
    }
    return super.onSubmit(request, response, issue, e);
}

From source file:com.aboutdata.service.bean.ImageGraphicsServiceImpl.java

/**
 * */* ww w  .j av a  2 s.  c  o  m*/
 * ????
 *
 * @param memberID
 * @param multipartFile
 */
@Override
public void buildAvatar(String memberID, MultipartFile multipartFile) {
    try {
        //image/png  image/gif
        String type = multipartFile.getContentType().split("/")[1];
        //ID.png ID-200.png 200
        File destFile = new File("/var/avatars/" + memberID + "." + type);
        multipartFile.transferTo(destFile);

        EasyImage image = new EasyImage(destFile);
        float width = image.getWidth();
        //?? 200
        int resize = (int) ((200 / width) * 100);
        image.resize(resize);
        //?/var/avatars/
        image.saveAs("/var/avatars/" + memberID + "-200" + "." + type);

    } catch (IOException | IllegalStateException ex) {
        logger.error("update user ({}) avatar failure,Image File name is ({}) ", memberID,
                multipartFile.getOriginalFilename());
        logger.error("{}", ex);
    }
}

From source file:net.shopxx.service.impl.ThemeServiceImpl.java

public boolean upload(MultipartFile multipartFile) {
    if (multipartFile == null || multipartFile.isEmpty()) {
        return false;
    }//  w w  w  .  j a  va2s. c o  m
    File tempThemeFile = new File(FileUtils.getTempDirectory(), UUID.randomUUID() + ".tmp");
    File tempThemeDir = new File(FileUtils.getTempDirectory(), UUID.randomUUID().toString());
    try {
        multipartFile.transferTo(tempThemeFile);
        CompressUtils.extract(tempThemeFile, tempThemeDir);
        File themeXmlFile = new File(tempThemeDir, "/template/theme.xml");
        if (themeXmlFile.exists() && themeXmlFile.isFile()) {
            Theme theme = get(themeXmlFile);
            if (theme != null && StringUtils.isNotEmpty(theme.getId())) {
                FileUtils.moveDirectory(new File(tempThemeDir, "/template"),
                        new File(servletContext.getRealPath(themeTemplatePath), theme.getId()));
                FileUtils.moveDirectory(new File(tempThemeDir, "/resources"),
                        new File(servletContext.getRealPath(themeResourcePath), theme.getId()));
                return true;
            }
        }
    } catch (IllegalStateException e) {
        throw new RuntimeException(e.getMessage(), e);
    } catch (IOException e) {
        throw new RuntimeException(e.getMessage(), e);
    } finally {
        FileUtils.deleteQuietly(tempThemeFile);
        FileUtils.deleteQuietly(tempThemeDir);
    }
    return false;
}

From source file:com.climate.oada.dao.impl.S3ResourceDAO.java

/**
 * Save file being uploaded to local./*w w w .  j a  va2s .co  m*/
 *
 * @param file
 *            - MultipartFile
 * @return File - Saved file.
 * @throws Exception
 *             in case of upload errors.
 */
File saveLocal(MultipartFile file) throws Exception {
    String uploadFileName = file.getOriginalFilename();
    File localfile = new File(uploadFileName);
    LOG.debug("Saving uploaded multipart file " + uploadFileName + " to local, file name "
            + localfile.getAbsolutePath());
    file.transferTo(localfile);
    return localfile;
}

From source file:it.cilea.osd.jdyna.web.controller.ImportAnagraficaObject.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 w w w  . jav  a  2  s.c om
 */
@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() });
    } catch (XmlBeanDefinitionStoreException exc) {
        //cancello il file dalla directory temporanea
        logger.warn("Error during the configuration import from 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.getBeanDefinitionNames(); //getBeanNamesForType(tpClass);
    AnagraficaObject<P, TP> anagraficaObject = null;

    String idStringAnagraficaObject = request.getParameter("id");
    Integer pkey = Integer.parseInt(idStringAnagraficaObject);
    anagraficaObject = applicationService.get(modelClass, pkey);

    //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 {
            ImportPropertyAnagraficaUtil importBean = (ImportPropertyAnagraficaUtil) context
                    .getBean(tpNameDefinition);
            anagraficaUtils.importProprieta(anagraficaObject, importBean);
        } catch (Exception ecc) {
            saveMessage(request, getText("action.file.nosuccess.metadato.upload",
                    new Object[] { ecc.getMessage() }, request.getLocale()));
            j++;
            i--;
        }
        i++;
    }
    //pulisco l'anagrafica
    anagraficaObject.pulisciAnagrafica();
    applicationService.saveOrUpdate(modelClass, anagraficaObject);

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

    return new ModelAndView(getDetailsView());
}

From source file:jetbrains.buildServer.clouds.azure.asm.web.CertificateController.java

@Override
protected ModelAndView doPost(final HttpServletRequest request, final HttpServletResponse response) {
    final ModelAndView modelAndView = new ModelAndView("/_fileUploadResponse.jsp");
    final String fileName = request.getParameter("fileName");
    boolean exists;
    try {/* ww  w.  j av a  2 s  .  c  o  m*/
        final MultipartFile file = getMultipartFileOrFail(request, "file:fileToUpload");
        if (file == null) {
            return error(modelAndView, "No file set");
        }
        final File pluginDataDirectory = FileUtil.createDir(new File(""));
        final File destinationFile = new File(pluginDataDirectory, fileName);
        exists = destinationFile.exists();
        file.transferTo(destinationFile);
    } catch (IOException e) {
        return error(modelAndView, e.getMessage());
    } catch (IllegalStateException e) {
        return error(modelAndView, e.getMessage());
    }

    if (exists) {
        Loggers.SERVER.info("File " + fileName + " is overwritten");
        ActionMessages.getOrCreateMessages(request).addMessage("mavenSettingsUploaded",
                "Maven settings file " + fileName + " was updated");
    } else {
        ActionMessages.getOrCreateMessages(request).addMessage("mavenSettingsUploaded",
                "Maven settings file " + fileName + " was uploaded");
    }

    return modelAndView;
}

From source file:org.craftercms.search.controller.SearchRestController.java

@RequestMapping(value = URL_UPDATE_DOCUMENT, method = RequestMethod.POST)
@ResponseBody//from w w w  .  jav  a  2s . c o m
public String updateDocument(@RequestPart(REQUEST_PARAM_SITE) String site,
        @RequestPart(REQUEST_PARAM_ID) String id, @RequestPart(REQUEST_PARAM_DOCUMENT) MultipartFile document,
        HttpServletRequest request) throws SearchException {

    try {
        File tmpFile = File.createTempFile("crafter" + document.getOriginalFilename(), "");
        Map<String, String> additionalFields = getAdditionalFields(request);

        document.transferTo(tmpFile);

        String result = searchService.updateDocument(site, id, tmpFile, additionalFields);

        FileUtils.forceDelete(tmpFile);

        return result;
    } catch (IOException e) {
        throw new SearchException(e);
    }
}

From source file:org.craftercms.search.controller.SearchRestController.java

@RequestMapping(value = URL_PARTIAL_DOCUMENT_UPDATE, method = RequestMethod.POST)
@ResponseBody/*from ww  w.ja va2s  . co m*/
public String partialDocumentUpdate(@RequestPart(REQUEST_PARAM_SITE) String site,
        @RequestPart(REQUEST_PARAM_ID) String id, @RequestPart(REQUEST_PARAM_DOCUMENT) MultipartFile document,
        HttpServletRequest request) throws SearchException {

    try {
        File tmpFile = File.createTempFile("crafter" + document.getOriginalFilename(), "");
        Map<String, String> additionalFields = getAdditionalFields(request);

        document.transferTo(tmpFile);

        String result = searchService.updateDocument(site, id, tmpFile, additionalFields);

        FileUtils.forceDelete(tmpFile);

        return result;
    } catch (IOException e) {
        throw new SearchException(e);
    }
}

From source file:com.vermeg.convertisseur.service.ConvServiceImpl.java

/**
 *
 * @param file/*from  w w  w . ja  v a 2 s  .co m*/
 * @return
 * @throws FileNotFoundException
 * @throws InvalidFormatException
 * @throws IOException
 */
/*this method convert a multipart file to json object */
@Override
public JSONObject convert(MultipartFile file, String name)
        throws FileNotFoundException, InvalidFormatException, IOException {

    // File file = new File("C:\\Users\\Ramzi\\Documents\\PFE\\developpement\\avancement.xlsx");

    File filez = File.createTempFile("fichier", "xslx");
    file.transferTo(filez);
    FileInputStream inp = new FileInputStream(filez);
    Workbook workbook = WorkbookFactory.create(inp);
    //Sheet sheet = workbook.getSheetAt( 0 );
    Sheet sheet = workbook.getSheet(name);
    // Start constructing JSON.
    JSONObject json = new JSONObject();

    // Iterate through the rows.
    JSONArray rows = new JSONArray();
    for (Iterator<Row> rowsIT = sheet.rowIterator(); rowsIT.hasNext();) {
        Row row = rowsIT.next();
        JSONObject jRow = new JSONObject();

        // Iterate through the cells.
        JSONArray cells = new JSONArray();
        for (Iterator<Cell> cellsIT = row.cellIterator(); cellsIT.hasNext();) {
            Cell cell = cellsIT.next();
            // System.out.println(cell.getCellType());
            //           cells.put(cell.getDateCellValue());
            switch (cell.getCellType()) {
            case Cell.CELL_TYPE_STRING:
                cells.put(cell.getRichStringCellValue().getString());
                break;
            case Cell.CELL_TYPE_NUMERIC:
                if (DateUtil.isCellDateFormatted(cell)) {
                    cells.put(cell.getDateCellValue());
                } else {
                    cells.put(cell.getNumericCellValue());
                }
                break;
            case Cell.CELL_TYPE_BOOLEAN:
                cells.put(cell.getBooleanCellValue());
                break;
            case Cell.CELL_TYPE_FORMULA:
                cells.put(cell.getCellFormula());
                break;
            default:
                System.out.println();
            }
        }
        jRow.put("cell", cells);
        rows.put(cells);
        //rows.put( jRow );
    }

    // Create the JSON.
    json.put("rows", rows);
    System.out.println(json.toString());
    return json;
}