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.web.controller.ToolController.java

@ResponseBody
@RequestMapping(value = "/tool/verifyapk", method = RequestMethod.POST)
public String verifyApk(@RequestParam("apkfile") MultipartFile file) {

    //keytool -list -printcert -jarfile d:\weixin653android980.apk
    //keytool -printcert -file D:\testapp\META-INF\CERT.RSA
    //System.out.println("12345");
    try {//w  ww  .ja  v  a2s .c  o  m
        OutputStream stream = new FileOutputStream(new File(file.getOriginalFilename()));
        BufferedOutputStream outputStream = new BufferedOutputStream(stream);
        outputStream.write(file.getBytes());
        outputStream.flush();
        outputStream.close();

        Runtime runtime = Runtime.getRuntime();
        String ccString = "keytool -list -printcert -jarfile C:\\Users\\Administrator\\Desktop\\zju1.1.8.2.apk";
        Process p = runtime.exec(ccString);

        BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));

        StringBuilder sb = new StringBuilder();
        while (br.readLine() != null) {
            sb.append(br.readLine() + "<br/>");
        }
        p.destroy();
        p = null;
        return sb.toString();
    } catch (FileNotFoundException fe) {
        return fe.getMessage();
    } catch (IOException ioe) {
        return ioe.getMessage();
    }

}

From source file:com.company.project.web.controller.FileUploadController.java

@RequestMapping(value = "/singleSave", method = RequestMethod.POST)
public @ResponseBody String singleSave(@RequestParam("file") MultipartFile file,
        @RequestParam("desc") String desc) {
    System.out.println("File Description:" + desc);
    String fileName = null;//from   w  ww.  j a  v  a 2  s . c o  m
    if (!file.isEmpty()) {
        try {
            fileName = file.getOriginalFilename();
            byte[] bytes = file.getBytes();
            BufferedOutputStream buffStream = new BufferedOutputStream(
                    new FileOutputStream(new File("C:/cp/" + fileName)));
            buffStream.write(bytes);
            buffStream.close();
            return "You have successfully uploaded " + fileName;
        } catch (Exception e) {
            return "You failed to upload " + fileName + ": " + e.getMessage();
        }
    } else {
        return "Unable to upload. File is empty.";
    }
}

From source file:com.card.loop.xyz.controller.LearningObjectController.java

@RequestMapping(value = "/upload", method = RequestMethod.POST)
public String upload(@RequestParam(value = "title") String title, @RequestParam("author") String author,
        @RequestParam("description") String description, @RequestParam("file") MultipartFile file,
        @RequestParam("type") String type) {
    if (!file.isEmpty()) {
        try {//from   w  w w.  j  av  a2 s.co m
            byte[] bytes = file.getBytes();
            File fil = new File(AppConfig.UPLOAD_BASE_PATH + file.getOriginalFilename());
            BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(fil));
            stream.write(bytes);
            stream.close();

            LearningObject lo = new LearningObject();
            System.out.println(title);
            System.out.println(author);
            System.out.println(description);

            lo.setTitle(title);
            lo.setUploadedBy(author);
            lo.setDateUpload(new Date());
            lo.setDescription(description);
            lo.setStatus(0);
            lo.setDownloads(0);
            lo.setRating(1);

            System.out.println("UPLOAD LO FINISHED");

        } catch (Exception e) {
            System.err.println(e.toString());
        }
    } else {
        System.err.println("EMPTY FILE.");
    }

    return "redirect:/developer-update";
}

From source file:com.oak_yoga_studio.controller.AdminController.java

@RequestMapping(value = "/addFaculty", method = RequestMethod.POST)
public String addFaculty(Faculty faculty, BindingResult result, HttpSession session,
        RedirectAttributes flashAttr, @RequestParam("file") MultipartFile file) {
    String view = "redirect:/viewFaculties";

    if (!result.hasErrors()) {
        try {//from  w  w  w. j a v  a  2  s  . c o m
            faculty.setProfilePicture(file.getBytes());
        } catch (IOException ex) {
            //Logger.getLogger(CustomerController.class.getName()).log(Level.SEVERE, null, ex);
        }
        faculty.getCredential().setActive(false);
        faculty.setActive(false);
        facultyServcie.addFaculty(faculty);
        session.removeAttribute("credential");
        flashAttr.addFlashAttribute("successful registered",
                "Faculty signed up succesfully. please  log in to proceed"); //           Customer c=(Customer) session.getAttribute("loggedCustomer");

    } else {
        for (FieldError err : result.getFieldErrors()) {
            System.out.println("Error:" + err.getField() + ":" + err.getDefaultMessage());
        }
        view = "addFaculty";
    }
    return view;
}

From source file:com.formkiq.core.api.FolderFilesController.java

/**
 * Save File to Folder./* ww w  .  j  ava  2  s  . c  o  m*/
 * @param request {@link HttpServletRequest}
 * @param response {@link HttpServletResponse}
 * @param folder {@link String}
 * @param entity HttpEntity&lt;byte[]&gt;
 * @param lastSha1hash {@link String}
 * @return {@link ApiMessageResponse}
 * @throws IOException IOException
 */
@Transactional
@RequestMapping(value = API_FOLDER_FILE + "/{folder}", method = POST)
public ApiMessageResponse saveFolderFile(final HttpServletRequest request, final HttpServletResponse response,
        @PathVariable(name = "folder", required = true) final String folder,
        @RequestParam(value = "sha1hash", required = false) final String lastSha1hash,
        final HttpEntity<byte[]> entity) throws IOException {

    getApiVersion(request);

    FormSaveResult result = null;
    ApiMessageResponse msg = new ApiMessageResponse("Save successful");

    Enumeration<String> e = request.getHeaders("accept");
    boolean isAdmin = this.securityService.isAdmin()
            && this.securityService.hasAcceptHeader(e, ACCEPT_HEADER_ADMIN);

    if (request instanceof MultipartHttpServletRequest) {

        MultipartHttpServletRequest rr = (MultipartHttpServletRequest) request;

        Iterator<String> itr = rr.getFileNames();
        MultipartFile mpf = rr.getFile(itr.next());
        result = this.folderService.saveForm(folder, mpf.getBytes(), lastSha1hash, isAdmin);
        checkForValidationErrors(result.getErrors());
        response.addHeader("sha1hash", result.getSha1hash());

    } else {

        result = this.folderService.saveForm(folder, entity.getBody(), lastSha1hash, isAdmin);
        checkForValidationErrors(result.getErrors());
        response.addHeader("sha1hash", result.getSha1hash());
    }

    if (FolderFormStatus.IN_PROCESS.equals(result.getStatus())) {
        msg = new ApiMessageResponse("Saved as 'In Process'");
    }

    return msg;
}

From source file:org.openmrs.module.patientsummary.web.controller.PatientSummaryTemplateEditor.java

@RequestMapping(method = RequestMethod.POST)
public String saveTemplate(String templateUuid, String name, Class<? extends ReportRenderer> rendererType,
        String properties, String script, String scriptType, boolean enableOnPatientDashboard,
        HttpServletRequest request, ModelMap model) throws IOException {

    PatientSummaryTemplate template = getService().getPatientSummaryTemplateByUuid(templateUuid);

    PatientSummaryWebConfiguration.saveEnableTemplateOnPatientDashboard(template, enableOnPatientDashboard);

    template.getReportDesign().setName(name);
    template.getReportDesign().setRendererType(rendererType);

    if (!template.getReportDesign().getRendererType().equals(TextTemplateRenderer.class)) {
        MultipartHttpServletRequest mpr = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> files = mpr.getFileMap();

        MultipartFile resource = files.values().iterator().next();

        if (resource != null && !resource.isEmpty()) {
            ReportDesignResource designResource = new ReportDesignResource();
            designResource.setReportDesign(template.getReportDesign());
            designResource.setContents(resource.getBytes());
            designResource.setContentType(resource.getContentType());

            String fileName = resource.getOriginalFilename();
            int index = fileName.lastIndexOf(".");
            designResource.setName(fileName.substring(0, index));
            designResource.setExtension(fileName.substring(index + 1));

            template.getReportDesign().addResource(designResource);
        }//w  ww.j  a v  a 2  s .co  m

        WidgetHandler propHandler = HandlerUtil.getPreferredHandler(WidgetHandler.class, Properties.class);
        Properties props = (Properties) propHandler.parse(properties, Properties.class);
        template.getReportDesign().setProperties(props);
    } else {
        template.getReportDesign().getProperties().clear();
        template.getReportDesign().getResources().clear();

        ReportDesignResource designResource = new ReportDesignResource();
        designResource.setReportDesign(template.getReportDesign());
        designResource.setName("template");
        designResource.setContentType("text/html");
        designResource.setContents(script.getBytes("UTF-8"));

        template.getReportDesign().addResource(designResource);

        template.getReportDesign().addPropertyValue(TextTemplateRenderer.TEMPLATE_TYPE, scriptType);
    }

    getService().savePatientSummaryTemplate(template);

    model.put("templateUuid", template.getUuid());

    return "redirect:" + PatientSummaryWebConstants.MODULE_URL + "editTemplate.form";
}

From source file:com.wipro.ats.bdre.md.rest.TDUploaderAPI.java

@RequestMapping(value = "/uploadtr/{processIdValue}", method = RequestMethod.POST)
@ResponseBody//w  w w .  jav a  2 s  . c o  m
public RestWrapper uploadInTeradata(@PathVariable("processIdValue") Integer processIdValue,
        @RequestParam("file") MultipartFile file, Principal principal) {

    if (!file.isEmpty()) {
        try {

            String uploadedFilesDirectory = MDConfig.getProperty(UPLOADBASEDIRECTORY);
            String name = file.getOriginalFilename();
            byte[] bytes = file.getBytes();
            String monitorPath = null;
            LOGGER.info("processIDvalue is " + processIdValue);
            com.wipro.ats.bdre.md.dao.jpa.Process process = processDAO.get(processIdValue);
            LOGGER.info("Process fetched = " + process.getProcessId());
            List<Properties> propertiesList = propertiesDAO.getByProcessId(process);
            LOGGER.info("No.of Properties fetched= " + propertiesList.size());
            for (Properties property : propertiesList) {
                LOGGER.debug(
                        "property fetched is " + property.getId().getPropKey() + " " + property.getPropValue());
                if ("monitored-dir-name".equals(property.getId().getPropKey())) {
                    monitorPath = property.getPropValue();
                }
            }
            String uploadLocation = monitorPath;
            LOGGER.info("Upload location: " + uploadLocation);
            File fileDir = new File(uploadLocation);
            fileDir.mkdirs();
            File fileToBeSaved = new File(uploadLocation + "/" + name);
            BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(fileToBeSaved));
            stream.write(bytes);
            stream.close();
            LOGGER.debug("Uploaded file: " + fileToBeSaved);

            //Populating Uploaded file bean to return in RestWrapper
            UploadedFile uploadedFile = new UploadedFile();
            uploadedFile.setParentProcessId(processIdValue);
            // uploadedFile.setSubDir(subDir);
            uploadedFile.setFileName(name);
            uploadedFile.setFileSize(fileToBeSaved.length());
            LOGGER.debug("The UploadedFile bean:" + uploadedFile);
            LOGGER.info("File uploaded : " + uploadedFile + " uploaded by User:" + principal.getName());

            return new RestWrapper(uploadedFile, RestWrapper.OK);
        } catch (Exception e) {
            LOGGER.error(e);
            return new RestWrapper(e.getMessage(), RestWrapper.ERROR);
        }
    } else {
        return new RestWrapper("You failed to upload because the file was empty.", RestWrapper.ERROR);

    }
}

From source file:co.com.soinsoftware.altablero.utils.FileUtils.java

public boolean savePhotoInServer(final MultipartFile file, final String name) {
    boolean saved = false;
    final String fileName = PATH + name;
    if (file != null && !file.isEmpty()) {
        try {//www  .  ja  v  a 2s  .c o  m
            final String directory = fileName.substring(0, fileName.lastIndexOf(File.separator));
            final File dirFile = new File(directory);
            if (!dirFile.exists()) {
                dirFile.mkdirs();
            }
            final byte[] bytes = file.getBytes();
            final OutputStream os = new FileOutputStream(new File(fileName));
            try (final BufferedOutputStream stream = new BufferedOutputStream(os)) {
                stream.write(bytes);
                saved = true;
            }
        } catch (Exception ex) {
            LOGGER.error(ex.getMessage(), ex);
        }
    }
    return saved;
}

From source file:com.castlemock.web.basis.manager.FileManager.java

/**
 * The method uploads a list of MultipartFiles to the server. The output file directory is configurable and can be
 * configured in the main property file under the key "temp.file.directory"
 * @param files The list of files that should be uploaded
 * @return Returns the uploaded files as a list of files. The files have the new server path.
 * @throws IOException Throws an exception if the upload fails.
 *///from  w ww .j  a  v  a 2  s  . c o  m
public List<File> uploadFiles(final List<MultipartFile> files) throws IOException {
    final File fileDirectory = new File(tempFilesFolder);

    if (!fileDirectory.exists()) {
        fileDirectory.mkdirs();
    }

    final List<File> uploadedFiles = new ArrayList<File>();
    LOGGER.debug("Starting uploading files");
    for (MultipartFile file : files) {
        if (file.getOriginalFilename().isEmpty()) {
            continue;
        }

        LOGGER.debug("Uploading file: " + file.getOriginalFilename());
        final File serverFile = new File(
                fileDirectory.getAbsolutePath() + File.separator + file.getOriginalFilename());
        final byte[] bytes = file.getBytes();
        final BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(serverFile));
        try {
            stream.write(bytes);
            uploadedFiles.add(serverFile);
        } finally {
            stream.close();
        }
    }
    return uploadedFiles;
}

From source file:org.centralperf.controller.RunController.java

/**
 * Set results from an uploaded JTL file for an existing run
 * @param projectId   ID of the project (From URI)
 * @param runId   ID of the run (from URI)
 * @param file   JTL file/*from   w  w  w.  j  av  a2 s  .  com*/
 * @return   Redirection to run detail page
 */
@RequestMapping(value = "/project/{projectId}/run/{runId}/results", method = RequestMethod.POST)
public String uploadResults(@PathVariable("projectId") Long projectId, @ModelAttribute("runId") Long runId,
        @RequestParam("jtlFile") MultipartFile file) {

    Run run = runRepository.findOne(runId);

    // Get the jtl File
    try {
        String jtlContent = new String(file.getBytes());
        runService.insertResultsFromCSV(run, jtlContent);
    } catch (IOException e) {
    }
    return "redirect:/project/" + projectId + "/run/" + run.getId() + "/detail";
}