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

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

Introduction

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

Prototype

@Override
InputStream getInputStream() throws IOException;

Source Link

Document

Return an InputStream to read the contents of the file from.

Usage

From source file:np.com.drose.studentmanagementsystem.controller.ProjectController.java

public String fileUpload(@RequestParam("files") MultipartFile projectfile, RedirectAttributes redirectAttr)
        throws FileNotFoundException, IOException {

    if (!projectfile.isEmpty()) {
        File fileUploadPath = new File("/opt/files");
        File filePathToStore = File.createTempFile("project", ".pdf", fileUploadPath);
        if (!fileUploadPath.exists()) {
            fileUploadPath.mkdir();//from   w ww.j  a  v  a  2s  .  c o m
        }
        BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(filePathToStore));
        FileCopyUtils.copy(projectfile.getInputStream(), stream);
        redirectAttr.addFlashAttribute("message", "FIle with name" + filePathToStore.toString() + " is upload");
        return filePathToStore.toString();
    } else {
        redirectAttr.addFlashAttribute("message", "failed to upload file");
    }
    return null;
}

From source file:org.activiti.app.rest.editor.ModelResource.java

/**
 * POST /rest/models/{modelId}/editor/newversion -> create a new model version
 *///from w w  w .  j  a va2  s  . c o m
@RequestMapping(value = "/rest/models/{modelId}/newversion", method = RequestMethod.POST)
public ModelRepresentation importNewVersion(@PathVariable String modelId,
        @RequestParam("file") MultipartFile file) {
    InputStream modelStream = null;
    try {
        modelStream = file.getInputStream();
    } catch (Exception e) {
        throw new BadRequestException("Error reading file inputstream", e);
    }

    return modelService.importNewVersion(modelId, file.getOriginalFilename(), modelStream);
}

From source file:org.activiti.app.rest.runtime.AbstractRelatedContentResource.java

protected ContentItemRepresentation uploadFile(User user, MultipartFile file, String taskId,
        String processInstanceId) {
    if (file != null && file.getName() != null) {
        try {/*from  w  w w . jav a2  s .co m*/
            String contentType = file.getContentType();

            // temp additional content type check for IE9 flash uploads
            if (StringUtils.equals(file.getContentType(), "application/octet-stream")) {
                contentType = getContentTypeForFileExtension(file);
            }

            ContentItem contentItem = contentService.newContentItem();
            contentItem.setName(getFileName(file));
            contentItem.setProcessInstanceId(processInstanceId);
            contentItem.setTaskId(taskId);
            contentItem.setMimeType(contentType);
            contentItem.setCreatedBy(user.getId());
            contentItem.setLastModifiedBy(user.getId());
            contentService.saveContentItem(contentItem, file.getInputStream());

            return createContentItemResponse(contentItem);

        } catch (IOException e) {
            throw new BadRequestException("Error while reading file data", e);
        }

    } else {
        throw new BadRequestException("File to upload is missing");
    }
}

From source file:org.activiti.app.service.editor.ActivitiDecisionTableService.java

public ModelRepresentation importDecisionTable(HttpServletRequest request, MultipartFile file) {

    String fileName = file.getOriginalFilename();
    if (fileName != null && (fileName.endsWith(".dmn") || fileName.endsWith(".xml"))) {
        try {//from  ww  w  . j  a  va  2s .c  o m

            XMLInputFactory xif = XmlUtil.createSafeXmlInputFactory();
            InputStreamReader xmlIn = new InputStreamReader(file.getInputStream(), "UTF-8");
            XMLStreamReader xtr = xif.createXMLStreamReader(xmlIn);

            DmnDefinition dmnDefinition = dmnXmlConverter.convertToDmnModel(xtr);
            ObjectNode editorJsonNode = dmnJsonConverter.convertToJson(dmnDefinition);

            // remove id to avoid InvalidFormatException when deserializing
            editorJsonNode.remove("id");

            ModelRepresentation modelRepresentation = new ModelRepresentation();
            modelRepresentation.setName(dmnDefinition.getName());
            modelRepresentation.setDescription(dmnDefinition.getDescription());
            modelRepresentation.setModelType(AbstractModel.MODEL_TYPE_DECISION_TABLE);
            Model model = modelService.createModel(modelRepresentation, editorJsonNode.toString(),
                    SecurityUtils.getCurrentUserObject());
            return new ModelRepresentation(model);

        } catch (Exception e) {
            logger.error("Could not import decision table model", e);
            throw new InternalServerErrorException("Could not import decision table model");
        }
    } else {
        throw new BadRequestException(
                "Invalid file name, only .dmn or .xml files are supported not " + fileName);
    }

}

From source file:org.activiti.rest.dmn.service.api.repository.DmnDeploymentCollectionResource.java

@RequestMapping(value = "/dmn-repository/deployments", method = RequestMethod.POST, produces = "application/json")
public DmnDeploymentResponse uploadDeployment(
        @RequestParam(value = "tenantId", required = false) String tenantId, HttpServletRequest request,
        HttpServletResponse response) {//from ww w. j  a  v a  2  s .com

    if (request instanceof MultipartHttpServletRequest == false) {
        throw new ActivitiIllegalArgumentException("Multipart request is required");
    }

    MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;

    if (multipartRequest.getFileMap().size() == 0) {
        throw new ActivitiIllegalArgumentException("Multipart request with file content is required");
    }

    MultipartFile file = multipartRequest.getFileMap().values().iterator().next();

    try {
        DmnDeploymentBuilder deploymentBuilder = dmnRepositoryService.createDeployment();
        String fileName = file.getOriginalFilename();
        if (StringUtils.isEmpty(fileName) || !(fileName.endsWith(".dmn") || fileName.endsWith(".xml"))) {
            fileName = file.getName();
        }

        if (fileName.endsWith(".dmn") || fileName.endsWith(".xml")) {
            deploymentBuilder.addInputStream(fileName, file.getInputStream());
        } else {
            throw new ActivitiIllegalArgumentException("File must be of type .xml or .dmn");
        }
        deploymentBuilder.name(fileName);

        if (tenantId != null) {
            deploymentBuilder.tenantId(tenantId);
        }

        DmnDeployment deployment = deploymentBuilder.deploy();

        response.setStatus(HttpStatus.CREATED.value());

        return dmnRestResponseFactory.createDmnDeploymentResponse(deployment);

    } catch (Exception e) {
        if (e instanceof ActivitiException) {
            throw (ActivitiException) e;
        }
        throw new ActivitiException(e.getMessage(), e);
    }
}

From source file:org.activiti.rest.form.service.api.repository.FormDeploymentCollectionResource.java

@RequestMapping(value = "/form-repository/deployments", method = RequestMethod.POST, produces = "application/json")
public FormDeploymentResponse uploadDeployment(
        @RequestParam(value = "tenantId", required = false) String tenantId, HttpServletRequest request,
        HttpServletResponse response) {//from  w ww .  j  a v a 2 s  .  com

    if (request instanceof MultipartHttpServletRequest == false) {
        throw new ActivitiIllegalArgumentException("Multipart request is required");
    }

    MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;

    if (multipartRequest.getFileMap().size() == 0) {
        throw new ActivitiIllegalArgumentException("Multipart request with file content is required");
    }

    MultipartFile file = multipartRequest.getFileMap().values().iterator().next();

    try {
        FormDeploymentBuilder deploymentBuilder = formRepositoryService.createDeployment();
        String fileName = file.getOriginalFilename();
        if (StringUtils.isEmpty(fileName) || !(fileName.endsWith(".form") || fileName.endsWith(".xml"))) {
            fileName = file.getName();
        }

        if (fileName.endsWith(".form") || fileName.endsWith(".xml")) {
            deploymentBuilder.addInputStream(fileName, file.getInputStream());
        } else {
            throw new ActivitiIllegalArgumentException("File must be of type .xml or .form");
        }
        deploymentBuilder.name(fileName);

        if (tenantId != null) {
            deploymentBuilder.tenantId(tenantId);
        }

        FormDeployment deployment = deploymentBuilder.deploy();
        response.setStatus(HttpStatus.CREATED.value());

        return formRestResponseFactory.createFormDeploymentResponse(deployment);

    } catch (Exception e) {
        if (e instanceof ActivitiException) {
            throw (ActivitiException) e;
        }
        throw new ActivitiException(e.getMessage(), e);
    }

}

From source file:org.aon.esolutions.appconfig.web.controller.EnvironmentController.java

@Transactional
@RequestMapping(value = "/{environmentName}/import", method = RequestMethod.POST)
public void importProperties(@PathVariable String applicationName, @PathVariable String environmentName,
        @RequestParam(value = "file") MultipartFile multipartFile,
        @RequestParam(value = "importMode") String importMode) {

    if (multipartFile.getName().endsWith(".xml") || multipartFile.getOriginalFilename().endsWith(".xml")) {
        new XmlImporter(applicationRepository, environmentRepository, updateUtility)
                .importFromXml(multipartFile, importMode);
        return;//from w w  w  .java2s.  c om
    }

    Environment env = updateUtility.getEnvironmentForWrite(applicationName, environmentName);

    if (env != null) {
        Properties props = new Properties();

        try {
            props.load(multipartFile.getInputStream());
        } catch (IOException e) {
            logger.error("Error importing properties", e);
            throw new IllegalArgumentException("Uploaded file does not look like a properties file");
        }

        if ("full".equals(importMode)) {
            env.clearVariables();
        } else if ("newOnly".equals(importMode)) {
            for (Entry<String, String> entry : env.getVariableEntries()) {
                props.remove(entry.getKey());
            }
        }

        for (Object key : props.keySet()) {
            env.put((String) key, props.getProperty((String) key));
            env.getEncryptedVariables().remove((String) key);
        }

        updateUtility.saveEnvironment(env);
    }
}

From source file:org.apache.openmeetings.servlet.outputhandler.BackupImportController.java

@RequestMapping(value = "/backup.upload", method = RequestMethod.POST)
public void service(HttpServletRequest request, HttpServletResponse httpServletResponse)
        throws ServletException, IOException {

    UploadInfo info = validate(request, true);
    try {//  w  ww .  ja v a2s  . c  o m
        MultipartFile multipartFile = info.file;
        InputStream is = multipartFile.getInputStream();
        performImport(is);

        UploadCompleteMessage uploadCompleteMessage = new UploadCompleteMessage(info.userId, "library", //message
                "import", //action
                "", //error
                info.filename);

        scopeApplicationAdapter.sendUploadCompletMessageByPublicSID(uploadCompleteMessage, info.publicSID);

    } catch (Exception e) {

        log.error("[ImportExport]", e);

        e.printStackTrace();
        throw new ServletException(e);
    }

    return;
}

From source file:org.apache.openmeetings.servlet.outputhandler.UploadController.java

@RequestMapping(value = "/file.upload", method = RequestMethod.POST)
public void handleFileUpload(HttpServletRequest request, HttpServletResponse response, HttpSession session)
        throws ServletException {
    UploadInfo info = validate(request, false);
    try {/*w ww.j  av  a  2 s  . c  o  m*/
        String room_idAsString = request.getParameter("room_id");
        if (room_idAsString == null) {
            throw new ServletException("Missing Room ID");
        }

        Long room_id_to_Store = Long.parseLong(room_idAsString);

        String isOwnerAsString = request.getParameter("isOwner");
        if (isOwnerAsString == null) {
            throw new ServletException("Missing isOwnerAsString");
        }
        boolean isOwner = false;
        if (isOwnerAsString.equals("1")) {
            isOwner = true;
        }

        String parentFolderIdAsString = request.getParameter("parentFolderId");
        if (parentFolderIdAsString == null) {
            throw new ServletException("Missing parentFolderId ID");
        }
        Long parentFolderId = Long.parseLong(parentFolderIdAsString);

        MultipartFile multipartFile = info.file;
        InputStream is = multipartFile.getInputStream();
        log.debug("fileSystemName: " + info.filename);

        ConverterProcessResultList returnError = fileProcessor.processFile(info.userId, room_id_to_Store,
                isOwner, is, parentFolderId, info.filename, 0L, ""); // externalFilesId, externalType

        UploadCompleteMessage uploadCompleteMessage = new UploadCompleteMessage();
        uploadCompleteMessage.setUserId(info.userId);

        // Flash cannot read the response of an upload
        // httpServletResponse.getWriter().print(returnError);
        uploadCompleteMessage.setMessage("library");
        uploadCompleteMessage.setAction("newFile");

        uploadCompleteMessage.setFileExplorerItem(
                fileExplorerItemDao.getFileExplorerItemsById(returnError.getFileExplorerItemId()));

        uploadCompleteMessage.setHasError(returnError.hasError());
        //we only send the complete log to the client if there is really something 
        //to show because of an error
        if (returnError.hasError()) {
            uploadCompleteMessage.setError(returnError.getLogMessage());
        }
        uploadCompleteMessage.setFileName(returnError.getCompleteName());

        sendMessage(info, uploadCompleteMessage);
    } catch (ServletException e) {
        throw e;
    } catch (Exception e) {
        log.error("Exception during upload: ", e);
        throw new ServletException(e);
    }
}