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:com.engine.biomine.BiomineController.java

@ApiOperation(
        // Populates the "summary"
        value = "Index multiple documents (from local)",
        // Populates the "description"
        notes = "Add multiple documents to the index (should be compressed in an archive file)")
@ApiResponses(value = { @ApiResponse(code = 200, message = "Accepted", response = Boolean.class),
        @ApiResponse(code = 400, message = "Bad Request", response = BiomineError.class),
        @ApiResponse(code = 500, message = "Internal Server Error", response = BiomineError.class),
        @ApiResponse(code = 503, message = "Service Unavailable", response = BiomineError.class) })
@RequestMapping(value = "/indexer/index/documents", method = RequestMethod.POST, produces = {
        APPLICATION_JSON_VALUE })//from ww w. ja  v a  2 s  . com
@ResponseBody
public ResponseEntity<Boolean> indexDocuments(
        @ApiParam(value = "File path", required = true) @RequestParam(value = "path", required = true) MultipartFile path,
        @ApiParam(value = "Collection", required = true) @RequestParam(value = "collection", required = true) String collection) {
    if (!path.isEmpty()) {
        if (IOUtil.getINSTANCE().isValidExtension(path.getOriginalFilename())) {
            logger.info("Start indexing data from path {}", path.getOriginalFilename());
            try {
                File file = new File(path.getOriginalFilename());
                file.createNewFile();

                FileOutputStream output = new FileOutputStream(file);
                output.write(path.getBytes());
                output.close();

                indexer.pushData(file, deleteFile, collection);

            } catch (IOException e) {
                e.printStackTrace();
            }
        } else
            logger.info("File extension not valid. Please select a valid file.");
    } else
        logger.info("File does not exist. Please select a valid file.");
    return new ResponseEntity<Boolean>(true, HttpStatus.OK);
}

From source file:quanlyhocvu.api.web.controller.staff.ManagementStudentController.java

@RequestMapping(value = "nhap_hocsinh", headers = "content-type=multipart/*", method = RequestMethod.POST)
public @ResponseBody ModelAndView importHocSinh(
        @RequestParam(value = "danhSachHocSinh", required = false) MultipartFile danhSachHocSinh)
        throws IOException {
    Map<String, Object> map = new HashMap<String, Object>();
    //        File file = new File(servletContext.getRealPath("/") + "/"
    //                    + filename);
    //String path = servletContext.getRealPath("/");                
    KhoiLopDTO khoiLop = mongoService.getKhoiLopByName("6");
    //System.out.println(request.getParameter("danhSachHocSinh"));
    //System.out.println(path);
    File temp_file = new File("uploaded.xls");
    byte[] bytes = danhSachHocSinh.getBytes();
    BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(temp_file));
    stream.write(bytes);/*from   w  w  w .j  av  a2 s  . com*/
    stream.close();
    System.out.println(danhSachHocSinh.getOriginalFilename());
    Workbook w;
    try {
        w = Workbook.getWorkbook(temp_file);
        //Get the first sheet
        Sheet sheet = w.getSheet(0);
        for (int i = 1; i < sheet.getRows(); i++) {
            HocSinhDTO hs = new HocSinhDTO();
            //Do columns co 6 cot nen se lay 6 cot
            Cell[] listCell = new Cell[7];
            for (int j = 0; j < 7; j++) {
                listCell[j] = sheet.getCell(j, i);
            }

            String hoTen = listCell[1].getContents();
            hs.sethoTen(hoTen);

            String gioiTinh = listCell[2].getContents();
            if (gioiTinh == "Nam") {
                hs.setgioiTinh(1);
            } else {
                hs.setgioiTinh(0);
            }

            String ngaySinh = listCell[3].getContents();
            Date ngaySinhDate = FunctionService.formatStringDateExcel(ngaySinh);
            hs.setngaySinh(ngaySinhDate);

            String ngayNhapHoc = listCell[4].getContents();
            Date ngayNhapHocDate = FunctionService.formatStringDateExcel(ngayNhapHoc);
            hs.setngayNhapHoc(ngayNhapHocDate);

            String diaChi = listCell[5].getContents();
            hs.setdiaChi(diaChi);

            String moTa = listCell[6].getContents();
            hs.setmoTa(moTa);
            hs.setKhoiLopHienTai(khoiLop);
            mongoService.insertStudent(hs);
        }
    } catch (BiffException ex) {
        java.util.logging.Logger.getLogger(ManagementStudentController.class.getName()).log(Level.SEVERE, null,
                ex);
    }
    return new ModelAndView("redirect:/staff/management/students/index", map);
}

From source file:net.mindengine.oculus.frontend.web.controllers.report.ReportUploadFileController.java

@Override
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
    response.setContentType("text/html");
    PrintWriter pw = response.getWriter();
    log.info("uploading file");
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    if (isMultipart) {

        DefaultMultipartHttpServletRequest multipartRequest = (DefaultMultipartHttpServletRequest) request;

        int i = 0;
        boolean bNext = true;
        while (bNext) {
            i++;// ww w .  jav a  2s. c  om
            MultipartFile multipartFile = multipartRequest.getFile("file" + i);
            if (multipartFile != null) {
                fileId++;
                Date date = new Date();
                String path = FileUtils.generatePath(date);
                String fullDirPath = config.getDataFolder() + File.separator + path;
                File dir = new File(fullDirPath);
                dir.mkdirs();
                //FileUtils.mkdirs(config.getDataFolder() + File.separator + path);

                String fileType = FileUtils.getFileType(multipartFile.getOriginalFilename()).toLowerCase();
                path += File.separator + date.getTime() + "_" + fileId + "." + fileType;

                File file = new File(config.getDataFolder() + File.separator + path);
                file.createNewFile();

                FileOutputStream fos = new FileOutputStream(file);
                fos.write(multipartFile.getBytes());
                fos.close();

                if (fileType.equals("png") || fileType.equals("jpg") || fileType.equals("gif")
                        || fileType.equals("bmp")) {
                    pw.println("[uploaded]?type=image-" + fileType + "&object=" + date.getTime() + "&item="
                            + fileId);
                }
                if (fileType.equals("txt") || fileType.equals("json") || fileType.equals("xml")) {
                    pw.println("[uploaded]?type=text-" + fileType + "&object=" + date.getTime() + "&item="
                            + fileId);
                }
            } else
                bNext = false;
        }
    } else
        pw.print("[error]not a multipart content");
    return null;
}

From source file:com.engine.biomine.BiomineController.java

@ApiOperation(
        // Populates the "summary"
        value = "Index biodata (from local)",
        // Populates the "description"
        notes = "Add a biodata file to the index")
@ApiResponses(value = { @ApiResponse(code = 200, message = "Accepted", response = Boolean.class),
        @ApiResponse(code = 400, message = "Bad Request", response = BiomineError.class),
        @ApiResponse(code = 500, message = "Internal Server Error", response = BiomineError.class),
        @ApiResponse(code = 503, message = "Service Unavailable", response = BiomineError.class) })
@RequestMapping(value = "/indexer/index/biodata/{data}", method = RequestMethod.POST, produces = {
        APPLICATION_JSON_VALUE })/*w w w . j a va  2s. c om*/
@ResponseBody
@ConfigurationProperties()
public ResponseEntity<Boolean> indexData(HttpServletResponse response,
        @ApiParam(value = "File", required = true) @RequestParam(value = "path", required = true) MultipartFile path,
        @ApiParam(value = "Collection", required = true) @RequestParam(value = "collection", required = true) String collection) {
    if (!path.isEmpty()) {
        if (IOUtil.getINSTANCE().isValidExtension(path.getOriginalFilename())) {
            logger.info("Start indexing data from path {}", path.getOriginalFilename());
            try {
                File file = new File(path.getOriginalFilename());
                file.createNewFile();
                deleteFile = false;

                FileOutputStream output = new FileOutputStream(file);
                output.write(path.getBytes());
                output.close();

                indexer.pushData(file, deleteFile, collection);

            } catch (IOException e) {
                e.printStackTrace();
            }
        } else
            logger.info("File extension not valid. Please select a valid file.");
    } else
        logger.info("File does not exist. Please select a valid file.");
    return new ResponseEntity<Boolean>(true, HttpStatus.OK);
}

From source file:com.balero.controllers.UploadController.java

/**
 * Upload image from CKEDITOR to server//from   ww w  . j  ava 2  s  .c o m
 *
 * Source: http://alfonsoml.blogspot.mx/2013/08/a-basic-
 * upload-script-for-ckeditor.html
 *
 * @param file HTML <input>
 * @param model Framework model layer
 * @param request HTTP headers
 * @param baleroAdmin Magic cookie
 * @return view
 */
@RequestMapping(value = "/picture", method = RequestMethod.POST)
public String uploadPicture(@RequestParam("upload") MultipartFile file, Model model, HttpServletRequest request,
        @CookieValue(value = "baleroAdmin", defaultValue = "init") String baleroAdmin) {

    // Security
    UsersAuth security = new UsersAuth();
    security.setCredentials(baleroAdmin, UsersDAO);
    boolean securityFlag = security.auth(baleroAdmin, security.getLocalUsername(), security.getLocalPassword());
    if (!securityFlag)
        return "hacking";

    String CKEditorFuncNum = request.getParameter("CKEditorFuncNum");

    String inputFileName = file.getOriginalFilename();

    if (!file.isEmpty()) {
        try {
            byte[] bytes = file.getBytes();

            // Creating the directory to store file
            //String rootPath = System.getProperty("catalina.home");
            File dir = new File("../webapps/media/pictures");
            if (!dir.exists())
                dir.mkdirs();

            String[] ext = new String[9];
            // Add your extension here
            ext[0] = ".jpg";
            ext[1] = ".png";
            ext[2] = ".bmp";
            ext[3] = ".jpeg";

            for (int i = 0; i < ext.length; i++) {
                int intIndex = inputFileName.indexOf(ext[i]);
                if (intIndex == -1) {
                    System.out.println("File extension is not valid");
                } else {
                    // Create the file on server
                    File serverFile = new File(dir.getAbsolutePath() + File.separator + inputFileName);
                    BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(serverFile));
                    stream.write(bytes);
                    stream.close();
                }
            }

            System.out.println("You successfully uploaded file");

        } catch (Exception e) {
            System.out.println("You failed to upload => " + e.getMessage());
        }
    } else {
        System.out.println("You failed to upload because the file was empty.");
    }

    //String url = request.getLocalAddr();

    model.addAttribute("url", "/media/pictures/" + inputFileName);
    model.addAttribute("CKEditorFuncNum", CKEditorFuncNum);

    return "upload";

}

From source file:com.engine.biomine.BiomineController.java

@ApiOperation(
        // Populates the "summary"
        value = "Index a doc (from local)",
        // Populates the "description"
        notes = "Add a single xml doc to the index")
@ApiResponses(value = { @ApiResponse(code = 200, message = "Accepted", response = Boolean.class),
        @ApiResponse(code = 400, message = "Bad Request", response = BiomineError.class),
        @ApiResponse(code = 500, message = "Internal Server Error", response = BiomineError.class),
        @ApiResponse(code = 503, message = "Service Unavailable", response = BiomineError.class) })
@RequestMapping(value = "/indexer/index/documents/{doc}", method = RequestMethod.POST, produces = {
        APPLICATION_JSON_VALUE })/*from   w  w w.jav a2 s .  c  o m*/
@ResponseBody
@ConfigurationProperties()
public ResponseEntity<Boolean> indexDocument(HttpServletResponse response,
        @ApiParam(value = "File path", required = true) @RequestParam(value = "path", required = true) MultipartFile path,
        @ApiParam(value = "Collection", required = true) @RequestParam(value = "collection", required = true) String collection) {
    if (!path.isEmpty()) {
        if (IOUtil.getINSTANCE().isValidExtension(path.getOriginalFilename())) {
            logger.info("Start indexing data from path {}", path.getOriginalFilename());
            try {
                File file = new File(path.getOriginalFilename());
                file.createNewFile();
                deleteFile = true;

                FileOutputStream output = new FileOutputStream(file);
                output.write(path.getBytes());
                output.close();

                indexer.pushData(file, deleteFile, collection);

            } catch (IOException e) {
                e.printStackTrace();
            }
        } else
            logger.info("File extension not valid. Please select a valid file.");
    } else
        logger.info("File does not exist. Please select a valid file.");
    return new ResponseEntity<Boolean>(true, HttpStatus.OK);
}

From source file:com.abixen.platform.core.service.impl.UserServiceImpl.java

@Override
public User changeUserAvatar(Long userId, MultipartFile avatarFile) throws IOException {
    User user = findUser(userId);// w w  w. j  a  v  a2  s  . co  m
    File currentAvatarFile = new File(platformResourceConfigurationProperties.getImageLibraryDirectory()
            + "/user-avatar/" + user.getAvatarFileName());
    if (currentAvatarFile.exists()) {
        if (!currentAvatarFile.delete()) {
            throw new FileExistsException();
        }
    }
    PasswordEncoder encoder = new BCryptPasswordEncoder();
    String newAvatarFileName = encoder.encode(avatarFile.getName() + new Date().getTime()).replaceAll("\"", "s")
            .replaceAll("/", "a").replace(".", "sde");
    File newAvatarFile = new File(platformResourceConfigurationProperties.getImageLibraryDirectory()
            + "/user-avatar/" + newAvatarFileName);
    FileOutputStream out = new FileOutputStream(newAvatarFile);
    out.write(avatarFile.getBytes());
    out.close();
    user.setAvatarFileName(newAvatarFileName);
    updateUser(user);
    return findUser(userId);
}

From source file:org.apigw.authserver.web.controller.ApplicationManagementController.java

private Certificate createCertificate(MultipartFile certificate, BindingResult result) {
    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());

    Certificate cert = new Certificate();
    if (certificate != null && certificate.getSize() > 0) {

        try {/*from w w w.j a va 2  s  . co  m*/
            PEMReader r = new PEMReader(
                    new InputStreamReader(new ByteArrayInputStream(certificate.getBytes())));
            Object certObj = r.readObject();

            long reference = System.currentTimeMillis();

            // validate certificate
            if (certObj instanceof X509Certificate) {
                X509Certificate x509cert = (X509Certificate) certObj;
                BigInteger serialNumber = x509cert.getSerialNumber();

                String issuerDn = x509cert.getIssuerDN().getName();
                String subjectDn = x509cert.getSubjectDN().getName();

                cert.setCertificate(certificate.getBytes());
                cert.setSerialNumber(serialNumber.toString());
                cert.setIssuer(issuerDn);
                cert.setSubject(subjectDn);
                cert.setSubjectCommonName(extractFromDn(subjectDn, "CN"));
                cert.setSubjectOrganization(extractFromDn(subjectDn, "O"));
                cert.setSubjectOrganizationUnit(extractFromDn(subjectDn, "OU"));
                cert.setSubjectLocation(extractFromDn(subjectDn, "L"));
                cert.setSubjectCountry(extractFromDn(subjectDn, "C"));
                cert.setNotAfter(x509cert.getNotAfter());
                cert.setNotBefore(x509cert.getNotBefore());
            } else {
                String line;
                StringBuilder certString = new StringBuilder();
                while ((line = r.readLine()) != null) {
                    certString.append(line + "\n");
                }
                log.warn(
                        "Bad certificate [{}]: Provided certificate was of the wrong type: {}. Certificate: \n{}",
                        new Object[] { reference, certObj, certString.toString() });
                result.rejectValue("certificates", "invalid.certificate",
                        "Certifikatet r ej giltigt (Reference: " + reference + ")");
            }

            r.close();
        } catch (IOException e) {
            log.warn("Bad certificate");
            result.rejectValue("certificates", "invalid.certificate", "Certifikatet r ej giltigt ");
        }
    }
    return cert;
}

From source file:controllers.admin.PostController.java

@PostMapping("/save")
public String processPost(@RequestPart("postImage") MultipartFile postImage,
        @ModelAttribute(ATTRIBUTE_NAME) @Valid Post post, BindingResult bindingResult,
        @CurrentUserAttached User activeUser, RedirectAttributes model) throws IOException, SQLException {

    String url = "redirect:/admin/posts/all";

    if (post.getImage() == null && postImage != null && postImage.isEmpty()) {
        bindingResult.rejectValue("image", "post.image.notnull");
    }// w ww.  ja va 2s .  com

    if (bindingResult.hasErrors()) {
        model.addFlashAttribute(BINDING_RESULT_NAME, bindingResult);
        return url;
    }

    if (postImage != null && !postImage.isEmpty()) {
        logger.info("Aadiendo informacin de la imagen");
        FileImage image = new FileImage();
        image.setName(postImage.getName());
        image.setContentType(postImage.getContentType());
        image.setSize(postImage.getSize());
        image.setContent(postImage.getBytes());
        post.setImage(image);
    }

    post.setAuthor(activeUser);
    if (post.getId() == null) {
        postService.create(post);
    } else {
        postService.edit(post);
    }

    List<String> successMessages = new ArrayList();
    successMessages.add(messageSource.getMessage("message.post.save.success", new Object[] { post.getId() },
            Locale.getDefault()));
    model.addFlashAttribute("successFlashMessages", successMessages);
    return url;
}

From source file:cz.zcu.kiv.eegdatabase.logic.controller.scenario.AddScenarioSchemaController.java

@Override
protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object command,
        BindException bindException) throws Exception {
    ModelAndView mav = new ModelAndView(getSuccessView());

    log.debug("Processing form data");
    AddScenarioSchemaCommand data = (AddScenarioSchemaCommand) command;

    String idString = request.getParameter("id");
    int id = 0;/*w  w w .j  a va 2s  .co m*/
    if (idString != null) {
        id = Integer.parseInt(idString);
    }

    MultipartFile schemaFile = data.getSchemaFile();

    ScenarioSchemas scenarioSchema;

    if (id > 0) {
        // Editing existing
        log.debug("Editing existing scenario schema.");
        scenarioSchema = scenarioSchemasDao.read(id);

    } else {
        // Creating new
        log.debug("Creating new scenario schema object");
        scenarioSchema = new ScenarioSchemas();
    }

    log.debug("Setting scenario schema description: " + data.getSchemaDescription());
    scenarioSchema.setDescription(data.getSchemaDescription());

    //set scenario schema file
    if ((schemaFile != null) && (!schemaFile.isEmpty())) {
        log.debug("Setting the scenario schema file");
        String schemaName = schemaFile.getOriginalFilename();
        scenarioSchema.setSchemaName(schemaName);
        byte[] schemaContent = schemaFile.getBytes();
        //Clob schemaContent = Hibernate.createClob(schemaFile.getBytes().toString());

        int newSchemaId = scenarioSchemasDao.getNextSchemaId();
        System.out.println(newSchemaId);
        ScenarioSchemaGenerator schemaGenerator = new ScenarioSchemaGenerator(newSchemaId, schemaName,
                schemaContent);
        String sql = schemaGenerator.generateSql();
        String hbmXml = schemaGenerator.generateHbmXml();
        String pojo = schemaGenerator.generatePojo();
        String bean = schemaGenerator.generateBean();

        scenarioSchema.setSql(Hibernate.createClob(sql));
        scenarioSchema.setHbmXml(Hibernate.createClob(hbmXml));
        scenarioSchema.setPojo(Hibernate.createClob(pojo));
        scenarioSchema.setBean(bean);
        scenarioSchema.setApproved('n');
    }

    log.debug("Saving scenario schema object");

    if (id > 0) {
        // Editing existing
        scenarioSchemasDao.update(scenarioSchema);
    } else {
        // Creating new
        scenarioSchemasDao.create(scenarioSchema);
    }

    log.debug("Returning MAV");
    return mav;
}