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.restfiddle.controller.rest.FileUploadController.java

@RequestMapping(value = "/api/import", method = RequestMethod.POST)
public @ResponseBody void upload(@RequestParam("projectId") String projectId, @RequestParam("name") String name,
        @RequestParam("file") MultipartFile file) {

    if (!file.isEmpty()) {
        try {/*from ww  w.  ja v a2s  .  c om*/
            byte[] bytes = file.getBytes();
            String fileContent = new String(bytes);
            JSONObject pmCollection = new JSONObject(fileContent);

            String collectionName = pmCollection.getString("name");
            System.out.println(collectionName);
            //
            Project project = projectController.findById(null, projectId);

            NodeDTO collectionNodeDTO = new NodeDTO();
            collectionNodeDTO.setName(collectionName);
            collectionNodeDTO.setNodeType(NodeType.FOLDER.name());
            collectionNodeDTO.setProjectId(projectId);

            NodeDTO collectionNode = nodeController.create(project.getProjectRef().getId(), collectionNodeDTO);

            JSONArray requests = pmCollection.getJSONArray("requests");
            int len = requests.length();
            for (int i = 0; i < len; i++) {
                JSONObject request = (JSONObject) requests.get(i);
                String requestName = request.getString("name");
                String requestDescription = request.getString("description");
                String requestUrl = request.getString("url");
                String requestMethod = request.getString("method");

                ConversationDTO conversationDTO = new ConversationDTO();
                RfRequestDTO rfRequestDTO = new RfRequestDTO();
                rfRequestDTO.setApiUrl(requestUrl);
                rfRequestDTO.setMethodType(requestMethod);

                String headersString = request.getString("headers");
                if (headersString != null && !headersString.isEmpty()) {
                    List<RfHeaderDTO> headerDTOs = new ArrayList<RfHeaderDTO>();
                    RfHeaderDTO headerDTO = null;
                    String[] headersArr = headersString.split("\n");
                    for (String header : headersArr) {
                        String[] headerToken = header.split(":");
                        String headerName = headerToken[0];
                        String headerValue = headerToken[1].trim();

                        headerDTO = new RfHeaderDTO();
                        headerDTO.setHeaderName(headerName);
                        headerDTO.setHeaderValue(headerValue);
                        headerDTOs.add(headerDTO);
                    }
                    rfRequestDTO.setHeaders(headerDTOs);
                }

                String dataMode = request.getString("dataMode");
                if ("raw".equals(dataMode)) {
                    String rawModeData = request.getString("rawModeData");
                    rfRequestDTO.setApiBody(rawModeData);
                } else if ("params".equals(dataMode)) {
                    JSONArray formParamsArr = request.getJSONArray("data");
                    int arrLen = formParamsArr.length();

                    FormDataDTO formParam = null;
                    List<FormDataDTO> formParams = new ArrayList<FormDataDTO>();
                    for (int j = 0; j < arrLen; j++) {
                        JSONObject formParamJSON = (JSONObject) formParamsArr.get(j);
                        formParam = new FormDataDTO();
                        formParam.setKey(formParamJSON.getString("key"));
                        formParam.setValue(formParamJSON.getString("value"));
                        formParams.add(formParam);
                    }
                    rfRequestDTO.setFormParams(formParams);
                }

                conversationDTO.setRfRequestDTO(rfRequestDTO);
                ConversationDTO createdConversation = conversationController.create(conversationDTO);
                conversationDTO.setId(createdConversation.getId());

                // Request Node
                NodeDTO childNode = new NodeDTO();
                childNode.setName(requestName);
                childNode.setDescription(requestDescription);
                childNode.setProjectId(projectId);
                childNode.setConversationDTO(conversationDTO);
                NodeDTO createdChildNode = nodeController.create(collectionNode.getId(), childNode);
                System.out.println("created node : " + createdChildNode.getName());
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
    }
}

From source file:com.linksinnovation.elearning.controller.api.CarouselController.java

@PreAuthorize("hasAuthority('Administrator')")
@RequestMapping(value = "/save", method = RequestMethod.POST)
public Carousel save(@RequestParam("id") Long id, @RequestParam("course") Long course,
        @RequestParam(value = "name", required = false) String name,
        @RequestParam(value = "file", required = false) MultipartFile file) throws Exception {
    Carousel carousel = carouselRepository.findOne(id);
    if (null != file) {
        String fileName = carousel.getId() + "-" + name;
        byte[] bytes = file.getBytes();
        try (BufferedOutputStream stream = new BufferedOutputStream(
                new FileOutputStream(new File("/mnt/data/images/slide/" + fileName)))) {
            stream.write(bytes);/*from   w  ww  .  ja  v a2  s.  co m*/
        }
        carousel.setImages(fileName);
    }
    carousel.setCourse(course);
    return carouselRepository.save(carousel);
}

From source file:eu.europa.ejusticeportal.dss.demo.web.controller.sign.SignController.java

/**
 * Upload a file //from ww w.  j  a  v a  2  s .c om
 * @param map the {@link ModelMap}
 * @param file the file to upload 
 * @param request the {@link HttpServletRequest}
 * @return the page mapping for choose sign method
 * @throws IOException
 */
@RequestMapping(value = FILE_HTML, method = RequestMethod.POST)
public String chooseFile(ModelMap map, @RequestParam("file") MultipartFile file, HttpServletRequest request)
        throws IOException {
    request.getSession().setAttribute(UPLOADED_FILE_KEY, file.getBytes());
    return CHOOSE_VIEW;
}

From source file:com.teasoft.teavote.controller.BackupController.java

@RequestMapping(value = "/api/teavote/verify-back-up", method = RequestMethod.POST)
@ResponseBody/*from   w  ww . j a  v  a 2s .c o m*/
public JSONResponse verify(@RequestParam("file") MultipartFile file, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    if (!file.isEmpty()) {
        byte[] fileBytes = file.getBytes();
        String pathToFileToVerify = new ConfigLocation().getConfigPath() + File.separator + "fileToVerify.sql";
        FileOutputStream fos = new FileOutputStream(pathToFileToVerify);
        fos.write(fileBytes);
        fos.close();

        if (sig.verifyFile(pathToFileToVerify)) {
            //Go ahead and restore database.
            String dbUserName = env.getProperty("teavote.user");
            String dbPassword = utilities.getPassword();
            if (!utilities.restoreDB(dbUserName, dbPassword, pathToFileToVerify)) {
                return new JSONResponse(false, 0, null,
                        Enums.JSONResponseMessage.SERVER_ERROR.toString() + ": Could not restore database");
            }
            //Delete the file
            new File(pathToFileToVerify).delete();
            return new JSONResponse(true, 0, null, Enums.JSONResponseMessage.SUCCESS.toString());
        } else {
            return new JSONResponse(false, 0, null, Enums.JSONResponseMessage.ACCESS_DENIED.toString()
                    + ": Digital Signature could not be verified");
        }
    }
    return new JSONResponse(false, 0, null, "Empty file");
}

From source file:org.lightadmin.core.web.RepositoryFilePropertyController.java

private Resource<FilePropertyValue> fileResource(Map.Entry<String, MultipartFile> fileEntry)
        throws IOException {
    MultipartFile multipartFile = fileEntry.getValue();

    FilePropertyValue filePropertyValue = new FilePropertyValue(multipartFile.getOriginalFilename(),
            multipartFile.getBytes());

    return new Resource<FilePropertyValue>(filePropertyValue);
}

From source file:com.orange.clara.cloud.poc.s3.controller.PocS3Controller.java

@RequestMapping(value = "/upload", method = RequestMethod.POST)
public String upload(@RequestParam("name") String name, @RequestParam("file") MultipartFile multipartFile,
        Model model) throws IOException {
    if (multipartFile.isEmpty()) {
        return "You failed to upload " + name + " because the file was empty.";
    }/* w  ww. j  a v  a 2  s  .c  om*/

    byte[] bytes = multipartFile.getBytes();
    Blob blob = this.blobStore.blobBuilder(name).payload(bytes).build();

    blobStore.putBlob(blob);
    model.addAttribute("message", "We uploaded the file '" + name + "' to a riakcs");
    return "success";
}

From source file:com.jaspersoft.jasperserver.war.themes.action.ThemeAction.java

public byte[] getFileContent(RequestContext context) throws Exception {
    MultipartFile multipartFile = context.getRequestParameters().getMultipartFile("themeZip");
    return multipartFile.getBytes();
}

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

@ExtDirectMethod(value = ExtDirectMethodType.FORM_POST, group = "itest_upload_service", event = "test", entryClass = String.class, synchronizeOnSession = true)
public ExtDirectFormPostResult uploadTest(@RequestParam("fileUpload") MultipartFile file, @Valid User user,
        BindingResult result) throws IOException {

    ExtDirectFormPostResult resp = new ExtDirectFormPostResult(result, false);

    if (file != null && !file.isEmpty()) {
        resp.addResultProperty("fileContents", new String(file.getBytes()));
        resp.addResultProperty("fileName", file.getOriginalFilename());
    }/*from   www . j a v a  2s .c  om*/

    resp.addResultProperty("name", user.getName());
    resp.addResultProperty("firstName", user.getFirstName());
    resp.addResultProperty("age", user.getAge());
    resp.addResultProperty("e-mail", user.getEmail());

    resp.setSuccess(true);
    return resp;
}

From source file:ch.ralscha.extdirectspring.provider.UploadService.java

@ExtDirectMethod(value = ExtDirectMethodType.FORM_POST, group = "group2", synchronizeOnSession = true)
public ExtDirectFormPostResult upload(@RequestParam("fileUpload") MultipartFile file, @Valid User user,
        BindingResult result) throws IOException {

    ExtDirectFormPostResult resp = new ExtDirectFormPostResult(result, false);

    if (file != null && !file.isEmpty()) {
        resp.addResultProperty("fileContents", new String(file.getBytes()));
        resp.addResultProperty("fileName", file.getOriginalFilename());
    }//  w  w w  .j  a v a2s .  c o  m

    resp.addResultProperty("name", user.getName());
    resp.addResultProperty("firstName", user.getFirstName());
    resp.addResultProperty("age", user.getAge());
    resp.addResultProperty("e-mail", user.getEmail());

    resp.setSuccess(true);
    return resp;
}

From source file:org.ow2.proactive.workflow_catalog.rest.controller.WorkflowController.java

@ApiOperation(value = "Creates a new workflow")
@ApiResponses(value = { @ApiResponse(code = 404, message = "Bucket not found"),
        @ApiResponse(code = 422, message = "Invalid XML workflow content supplied") })
@RequestMapping(value = "/buckets/{bucketId}/workflows", consumes = {
        MediaType.MULTIPART_FORM_DATA_VALUE }, method = POST)
@ResponseStatus(HttpStatus.CREATED)//ww w . j a  v a  2 s . c  om
public WorkflowMetadataList create(@PathVariable Long bucketId,
        @ApiParam(value = "Layout describing the tasks position in the Workflow") @RequestParam(required = false) Optional<String> layout,
        @ApiParam(value = "Import workflows from ZIP when set to 'zip'.") @RequestParam(required = false) Optional<String> alt,
        @RequestPart(value = "file") MultipartFile file) throws IOException {
    if (alt.isPresent() && ZIP_EXTENSION.equals(alt.get())) {
        return new WorkflowMetadataList(workflowService.createWorkflows(bucketId, layout, file.getBytes()));
    } else {
        return new WorkflowMetadataList(workflowService.createWorkflow(bucketId, layout, file.getBytes()));
    }
}