Example usage for org.springframework.web.multipart MultipartFile getBytes

List of usage examples for org.springframework.web.multipart MultipartFile getBytes

Introduction

In this page you can find the example usage for org.springframework.web.multipart MultipartFile getBytes.

Prototype

byte[] getBytes() throws IOException;

Source Link

Document

Return the contents of the file as an array of bytes.

Usage

From source file:equipeDFK.sistemaX.controller.ControllerAgenda.java

/**
 * Mtodo que recebe uma requisio para importar os feriados,
 * ento ler o arquivo CSV e depois persistir os dados no banco
 * @param arquivoCSV//ww w. jav a  2 s. c om
 * @param sobrescrever
 * @param req
 * @return String
 * @throws SQLException 
 */
@RequestMapping("openCSV")
public String OpenCSV(MultipartFile arquivoCSV, boolean sobrescrever, HttpServletRequest req)
        throws SQLException {
    GerenciadorDeFeriado gf = new GerenciadorDeFeriado();
    if (!arquivoCSV.isEmpty()) {
        try {
            byte[] b = arquivoCSV.getBytes();
            String caminho = req.getServletContext().getRealPath("/") + arquivoCSV.getOriginalFilename();
            System.out.println(caminho);
            BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(new File(caminho)));
            stream.write(b);
            stream.close();
            OpenCSV opencsv = new OpenCSV();
            if (sobrescrever) {

            } else {

            }
            gf.importaferiado(opencsv.lerCSV(new File(caminho)), sobrescrever);
            List eventos = gf.listar();
            eventos.stream().forEach((evento) -> {
                System.out.println(evento);
            });
            req.getSession().setAttribute("feriados", eventos);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
    return "managerHoliday";
}

From source file:com.opencart.controller.ProductController.java

@RequestMapping(value = "/product/upload", method = RequestMethod.POST)
public @ResponseBody ModelAndView handleFileUpload(@RequestParam("id") String id,
        @RequestParam("file") MultipartFile image, HttpServletRequest request) {
    if (!image.isEmpty()) {
        try {// w ww . j a v a  2 s  . c  o m
            File file = new File("c:/uploads/products/" + id + "/" + image.getOriginalFilename());

            FileUtils.writeByteArrayToFile(file, image.getBytes());
            Product product = productService.getById(Long.parseLong(id));
            product.setImg(file.getName());
            productService.update(product);

            List<Product> products = productService.list();
            ModelAndView mv = new ModelAndView("admin/product", "products", products);
            return mv;

        } catch (Exception e) {
            ModelAndView mv = new ModelAndView("admin/addProductImage");
            mv.addObject("id", id);
            return mv;
        }
    } else {
        ModelAndView mv = new ModelAndView("admin/addProductImage");
        mv.addObject("id", id);
        return mv;
    }
}

From source file:ch.ralscha.extdirectspring_itest.FileUploadController.java

@ExtDirectMethod(value = ExtDirectMethodType.FORM_POST, group = "itest_upload", event = "test", entryClass = String.class, synchronizeOnSession = true)
@RequestMapping(value = "/test", method = RequestMethod.POST)
public void uploadTest(HttpServletRequest request, @RequestParam("fileUpload") MultipartFile file,
        final HttpServletResponse response, @Valid User user, BindingResult result) throws IOException {

    ExtDirectResponseBuilder builder = new ExtDirectResponseBuilder(request, response);

    if (file != null && !file.isEmpty()) {
        builder.addResultProperty("fileContents", new String(file.getBytes()));
        builder.addResultProperty("fileName", file.getOriginalFilename());
    }//from   w w  w  . j av a  2  s  .com
    builder.addErrors(result);
    builder.addResultProperty("name", user.getName());
    builder.addResultProperty("firstName", user.getFirstName());
    builder.addResultProperty("age", user.getAge());
    builder.addResultProperty("email", user.getEmail());

    builder.successful();
    builder.buildAndWrite();
}

From source file:org.openmrs.module.hl7valuegroups.web.controller.HL7ValueGroupsManageController.java

@RequestMapping(method = RequestMethod.POST)
public void apply(@RequestParam("hl7") MultipartFile hl7) {
    if (hl7 == null || hl7.isEmpty())
        return;//  w w  w  .j a v a  2 s  . c  om

    log.warn("processing hl7 ...");
    HL7Service hl7Service = Context.getHL7Service();

    HL7InQueue queue = new HL7InQueue();
    queue.setHL7Source(hl7Service.getHL7Source(1));
    try {
        queue.setHL7Data(new String(hl7.getBytes()));
    } catch (IOException e) {
        log.warn("could not create hl7 from this data");
        return;
    }

    hl7Service.saveHL7InQueue(queue);
    log.warn("hl7 saved ...");
}

From source file:com.groupon.odo.controllers.BackupController.java

/**
 * Restore backup data//  ww w .  j av a  2s.  c  o  m
 *
 * @param fileData - json file with restore data
 * @return
 * @throws Exception
 */
@RequestMapping(value = "/api/backup", method = RequestMethod.POST)
public @ResponseBody Backup processBackup(@RequestParam("fileData") MultipartFile fileData) throws Exception {
    // Method taken from: http://spring.io/guides/gs/uploading-files/
    if (!fileData.isEmpty()) {
        try {
            byte[] bytes = fileData.getBytes();
            BufferedOutputStream stream = new BufferedOutputStream(
                    new FileOutputStream(new File("backup-uploaded.json")));
            stream.write(bytes);
            stream.close();

        } catch (Exception e) {
        }
    }
    File f = new File("backup-uploaded.json");
    BackupService.getInstance().restoreBackupData(new FileInputStream(f));
    return BackupService.getInstance().getBackupData();
}

From source file:it.polimi.diceH2020.launcher.controller.rest.RestFilesController.java

private File saveFile(MultipartFile file, String fileName) throws FileNameClashException, IOException {
    File outFile = fileUtility.provideFile(fileName);
    try (BufferedOutputStream buffStream = new BufferedOutputStream(new FileOutputStream(outFile))) {
        byte[] bytes = file.getBytes();
        buffStream.write(bytes);/*w  w  w.jav  a  2 s  . c  o  m*/
    }
    return outFile;
}

From source file:com.gisnet.cancelacion.web.controller.NotarioController.java

private void guardaCancelacionArchivo(MultipartFile file) throws IOException {
    CancelacionArchivoInfo archivo = new CancelacionArchivoInfo();
    archivo.setArchivo(file.getBytes());
    archivo.setNombre(file.getOriginalFilename());
    archivo.setMimetype(file.getContentType());
    sesion.getCancelacionArchivos().add(archivo);
}

From source file:org.pdfgal.pdfgalweb.utils.impl.FileUtilsImpl.java

@Override
public String saveFile(final MultipartFile file) {

    String name = null;/*from ww w  .j a va2s  .  c o  m*/

    if (!file.isEmpty()) {
        try {
            final String originalName = file.getOriginalFilename();
            name = this.getAutogeneratedName(originalName);
            final byte[] bytes = file.getBytes();
            final BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(new File(name)));
            stream.write(bytes);
            stream.close();
        } catch (final Exception e) {
            name = null;// TODO Incluir no log.
        }
    }

    return name;
}

From source file:hu.bme.iit.quiz.service.QuizServiceImpl.java

@Override
public String validateAndCreateQuizForUserFromFile(MultipartFile file, String quizName, String loginName) {
    String originalFileName = file.getOriginalFilename();
    if (!file.isEmpty()) {
        try {/*from  w w w  .j ava 2  s .  c  om*/
            byte[] bytes = file.getBytes();

            //Only XML files, no mime check, basic check
            if (!file.getOriginalFilename().toLowerCase().endsWith(".xml")) {
                return "You failed to upload " + originalFileName + " because it's not an XML file.";
            }

            // Creating the directory to store file
            String rootPath = System.getProperty("catalina.home");
            File dir = new File(rootPath + File.separator + "tmpFiles");
            if (!dir.exists()) {
                dir.mkdirs();
            }

            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-mm-dd-HH-mm-ss");
            Date now = new Date();
            String innerFileLocation = dateFormat.format(now) + "_" + originalFileName;

            // Create the file on server
            File serverFile = new File(dir.getAbsolutePath() + File.separator + innerFileLocation);
            BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(serverFile));
            stream.write(bytes);
            stream.close();

            //Persist it in db
            Quiz quiz = new Quiz();
            quiz.setName(quizName);
            quiz.setBlobdata(bytes);
            quiz.setLocation(innerFileLocation);
            quiz.setUploaded(new Date());
            quiz.setInnerkey(UUID.randomUUID().toString());
            quiz.setOwner(userDAO.getUser(loginName));

            if (getQuizDataFromXML(quiz) != null) {
                quizDAO.addQuiz(quiz);
            } else {
                return "Invalid XML file!";
            }

            logger.info("XML file uploaded: " + originalFileName);
            return "You successfully uploaded '" + originalFileName + "'";
        } catch (Exception e) {
            logger.error(e);
            e.printStackTrace();
            return "You failed to upload " + originalFileName + " => " + e.getMessage();
        }
    } else {
        return "You failed to upload " + originalFileName + " because the file was empty.";
    }
}

From source file:ru.langboost.controllers.file.FileController.java

@RequestMapping(value = "/file/upload", method = RequestMethod.POST, produces = "application/json")
public @ResponseBody List<File> upload(MultipartHttpServletRequest request, HttpServletResponse response) {
    List<File> files = new LinkedList<>();
    Iterator<String> fileNamesIterator = request.getFileNames();
    MultipartFile multipartFile = null;
    while (fileNamesIterator.hasNext()) {
        try {/*w w  w. j  a  v  a 2  s  .  c  o m*/
            multipartFile = request.getFile(fileNamesIterator.next());
            String fileName = multipartFile.getOriginalFilename();
            String contentType = multipartFile.getContentType();
            byte[] source = multipartFile.getBytes();
            File file = new File(source, contentType, fileName);
            files.add(file);
        } catch (IOException ex) {
        }
    }
    request.getSession().setAttribute(SESSION_FILES_NAME, files);
    return files;
}