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:controllers.CarPropertyController.java

@RequestMapping("/updateFromXml")
public String updateFromXml(Map<String, Object> model,
        @RequestParam(value = "xlsFile", required = false) MultipartFile file, RedirectAttributes ras) {
    if (file == null || file.isEmpty()) {
        ras.addFlashAttribute("error", "File not found");
    } else {/*from   w ww  .j a  v  a  2 s  . c  o  m*/
        File newFile = new File("/usr/local/etc/CarProperty");
        if (newFile.exists()) {
            newFile.delete();
        }
        try {
            FileUtils.writeByteArrayToFile(newFile, file.getBytes());
            carPropertyService.updateFromXml(newFile);
            ras.addFlashAttribute("error", carPropertyService.getResult().getErrors());
        } catch (Exception e) {
            ras.addFlashAttribute("error", "updateFromXml" + StringAdapter.getStackTraceException(e));
        }
        if (newFile.exists()) {
            newFile.delete();
        }
    }
    return "redirect:/CarProperty/show";
}

From source file:controllers.ColorController.java

@RequestMapping("/updateFromXml")
public String updateFromXml(Map<String, Object> model,
        @RequestParam(value = "xlsFile", required = false) MultipartFile file, RedirectAttributes ras) {
    if (file == null || file.isEmpty()) {
        ras.addFlashAttribute("error", "File not found");
    } else {/*from   www .  j ava2s  .  c  o  m*/
        File newFile = new File("/usr/local/etc/Color");
        if (newFile.exists()) {
            newFile.delete();
        }
        try {
            FileUtils.writeByteArrayToFile(newFile, file.getBytes());
            colorService.updateFromXml(newFile);
            ras.addFlashAttribute("error", colorService.getResult().getErrors());
        } catch (Exception e) {
            ras.addFlashAttribute("error", "updateFromXml" + e.getMessage());
        }
        if (newFile.exists()) {
            newFile.delete();
        }
    }
    return "redirect:/Color/show";
}

From source file:org.shaf.server.controller.ActionApplicationController.java

/**
 * Deploys an application to the server.
 * /*from w  ww  .  j  a va2  s  .c  om*/
 * @param file
 *            the deploying package.
 * @return the view model.
 * @throws Exception
 *             is the view constructing has failed.
 */
@RequestMapping(value = "/deploy", method = RequestMethod.POST)
public ModelAndView onDeploy(@RequestParam("file") MultipartFile file) throws Exception {
    LOG.debug("CALL: /app/action/deploy (with attached multipart-file object)");

    ViewApplication view = ViewApplication.getListView().header("cloud",
            "All currently deployed applications.");

    if (!file.isEmpty()) {
        String app = file.getOriginalFilename();
        if (OPER.deployApplication(app, file.getBytes())) {
            view.info("The '" + app + "' application is deployed. ");
        } else {
            view.warn("The '" + app + "' application is not deployed yet. "
                    + "(Check the log to clarify a problem.)");
        }
    } else {
        view.warn("Select an application for deployment " + "(click on 'Browse' button).");
    }

    return view.addApplicationList(OPER.getApplications());
}

From source file:controllers.CCOController.java

@RequestMapping("/updateFromXml")
public String updateFromXml(Map<String, Object> model,
        @RequestParam(value = "xlsFile", required = false) MultipartFile file, RedirectAttributes ras) {
    if (file == null || file.isEmpty()) {
        ras.addFlashAttribute("error", "File not found");
    } else {//from w  w  w  .  ja v  a2s .c  o m
        File newFile = new File("/usr/local/etc/CCO");
        if (newFile.exists()) {
            newFile.delete();
        }
        try {
            FileUtils.writeByteArrayToFile(newFile, file.getBytes());
            carCompletionOptionService.updateFromXml(newFile);
            ras.addFlashAttribute("error", carCompletionOptionService.getResult().getErrors());
        } catch (Exception e) {
            ras.addFlashAttribute("error", "updateFromXml" + e.getMessage());
        }
        if (newFile.exists()) {
            newFile.delete();
        }
    }
    return "redirect:/CCO/show";
}

From source file:controllers.ColorGroupController.java

@RequestMapping("/updateFromXml")
public String updateFromXml(Map<String, Object> model,
        @RequestParam(value = "xlsFile", required = false) MultipartFile file, RedirectAttributes ras) {
    if (file == null || file.isEmpty()) {
        ras.addFlashAttribute("error", "File not found");
    } else {/*  w w  w  .  jav a2s.c o  m*/
        File newFile = new File("/usr/local/etc/ColorGroup");
        if (newFile.exists()) {
            newFile.delete();
        }
        try {
            FileUtils.writeByteArrayToFile(newFile, file.getBytes());
            colorGroupService.updateFromXml(newFile);
            ras.addFlashAttribute("error", colorGroupService.getResult().getErrors());
        } catch (Exception e) {
            ras.addFlashAttribute("error", "updateFromXml" + e.getMessage());
        }
        if (newFile.exists()) {
            newFile.delete();
        }
    }
    return "redirect:/ColorGroup/show";
}

From source file:ua.aits.crc.controller.SystemController.java

@RequestMapping(value = { "/system/do/uploadimage", "/system/do/uploadimage/" }, method = RequestMethod.POST)
public @ResponseBody String uploadImageHandler(@RequestParam("file") MultipartFile file,
        @RequestParam("path") String path, HttpServletRequest request) {
    String name = file.getOriginalFilename();
    name = TransliteratorClass.transliterate(name);
    if (!file.isEmpty()) {
        try {/*from www. j a  v a  2s  .  co  m*/
            byte[] bytes = file.getBytes();
            File dir = new File(Constants.home + path);
            if (!dir.exists())
                dir.mkdirs();
            File serverFile = new File(dir.getAbsolutePath() + File.separator + name);
            try (BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(serverFile))) {
                stream.write(bytes);
            }
            return "";
        } catch (Exception e) {
            return "You failed to upload " + name + " => " + e.getMessage();
        }
    } else {
        return "You failed to upload " + name + " because the file was empty.";
    }
}

From source file:org.biopax.validator.ws.ValidatorController.java

/**
 * JSP pages and RESTful web services controller, the main one that checks BioPAX data.
 * All parameter names are important, i.e., these are part of public API (for clients)
 * /*from   w  w  w. ja  v  a 2s.c  o m*/
 * Framework's built-in parameters:
 * @param request the web request object (may contain multi-part data, i.e., multiple files uploaded)
 * @param response 
 * @param mvcModel Spring MVC Model
 * @param writer HTTP response writer
 * 
 * BioPAX Validator/Normalizer query parameters:
 * @param url
 * @param retDesired
 * @param autofix
 * @param filter
 * @param maxErrors
 * @param profile
 * @param normalizer binds to three boolean options: normalizer.fixDisplayName, normalizer.inferPropertyOrganism, normalizer.inferPropertyDataSource
 * @return
 * @throws IOException
 */
@RequestMapping(value = "/check", method = RequestMethod.POST)
public String check(HttpServletRequest request, HttpServletResponse response, Model mvcModel, Writer writer,
        @RequestParam(required = false) String url, @RequestParam(required = false) String retDesired,
        @RequestParam(required = false) Boolean autofix, @RequestParam(required = false) Behavior filter,
        @RequestParam(required = false) Integer maxErrors, @RequestParam(required = false) String profile,
        //normalizer!=null when called from the JSP; 
        //but it's usually null when from the validator-client or a web script
        @ModelAttribute("normalizer") Normalizer normalizer) throws IOException {
    Resource resource = null; // a resource to validate

    // create the response container
    ValidatorResponse validatorResponse = new ValidatorResponse();

    if (url != null && url.length() > 0) {
        if (url != null)
            log.info("url : " + url);
        try {
            resource = new UrlResource(url);
        } catch (MalformedURLException e) {
            mvcModel.addAttribute("error", e.toString());
            return "check";
        }

        try {
            Validation v = execute(resource, resource.getDescription(), maxErrors, autofix, filter, profile,
                    normalizer);
            validatorResponse.addValidationResult(v);
        } catch (Exception e) {
            return errorResponse(mvcModel, "check", "Exception: " + e);
        }

    } else if (request instanceof MultipartHttpServletRequest) {
        MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
        Map files = multiRequest.getFileMap();
        Assert.state(!files.isEmpty(), "No files to validate");
        for (Object o : files.values()) {
            MultipartFile file = (MultipartFile) o;
            String filename = file.getOriginalFilename();
            // a workaround (for some reason there is always a no-name-file;
            // this might be a javascript isue)
            if (file.getBytes().length == 0 || filename == null || "".equals(filename))
                continue;

            log.info("check : " + filename);

            resource = new ByteArrayResource(file.getBytes());

            try {
                Validation v = execute(resource, filename, maxErrors, autofix, filter, profile, normalizer);
                validatorResponse.addValidationResult(v);
            } catch (Exception e) {
                return errorResponse(mvcModel, "check", "Exception: " + e);
            }

        }
    } else {
        return errorResponse(mvcModel, "check", "No BioPAX input source provided!");
    }

    if ("xml".equalsIgnoreCase(retDesired)) {
        response.setContentType("application/xml");
        ValidatorUtils.write(validatorResponse, writer, null);
    } else if ("html".equalsIgnoreCase(retDesired)) {
        /* could also use ValidatorUtils.write with a xml-to-html xslt source
         but using JSP here makes it easier to keep the same style, header, footer*/
        mvcModel.addAttribute("response", validatorResponse);
        return "groupByCodeResponse";
    } else { // owl only
        response.setContentType("text/plain");
        // write all the OWL results one after another TODO any better solution?
        for (Validation result : validatorResponse.getValidationResult()) {
            if (result.getModelData() != null)
                writer.write(result.getModelData() + NEWLINE);
            else
                // empty result
                writer.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<rdf:RDF></rdf:RDF>" + NEWLINE);
        }
    }

    return null; // (Writer is used instead)
}

From source file:com.nts.alphamaleWeb.controller.ServiceController.java

@RequestMapping(value = "/importJobs", method = RequestMethod.POST)
@ResponseBody/*from www  .  j a v  a2  s . c om*/
public String importJobs(MultipartHttpServletRequest request, HttpServletResponse response) {

    ResultBody<String> result = new ResultBody<String>();
    Iterator<String> itr = request.getFileNames();
    MultipartFile mpf = null;

    Gson gson = new GsonBuilder().setPrettyPrinting().create();
    while (itr.hasNext()) {
        mpf = request.getFile(itr.next());
        try {
            String json = new String(mpf.getBytes());
            JsonArray arr = gson.fromJson(json, JsonArray.class);
            result.setCode(Code.OK, gson.toJson(arr));
        } catch (IOException e) {
            result.setCode(Code.F200);
        }
    }
    return result.toJson();
}

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

@RequestMapping(value = "/uploadccp", method = RequestMethod.POST)
public @ResponseBody String uploadCartaCancelacionPDF(@RequestParam("codigocarta") String codigocarta,
        @RequestParam("file") MultipartFile file) {

    CartaCancelacionInfo cc = new CartaCancelacionInfo();
    cc.setDireccion("na");
    cc.setEntidad("AG");
    cc.setFechaEmisionCarta(new Date());
    cc.setFojaEscritura("na");
    cc.setFolio("na");
    cc.setFolioEscritura("na");
    cc.setLibroEscritura("na");
    cc.setNombreAcreditado("na");
    cc.setNombreNotario("na");
    cc.setCodigoCarta(codigocarta);//from   w ww .  ja  v a  2 s .  c  om
    try {
        cc.setPdf(file.getBytes());
    } catch (IOException ex) {
        return "<pre>" + ex + "</pre>";
    }
    SaveResponse<CartaCancelacionInfo> save = ccps.save(new SaveRequest<>(cc));
    return "<pre>success, id=" + save.getInfo().getId() + "</pre>";
}

From source file:controllers.BaseParamController.java

@RequestMapping("/updateFromXml")
public String updateFromXml(Map<String, Object> model,
        @RequestParam(value = "xlsFile", required = false) MultipartFile file, RedirectAttributes ras) {
    if (file == null || file.isEmpty()) {
        ras.addFlashAttribute("error", "File not found");
    } else {//from   w ww.  j a v a 2s.  co m
        File newFile = new File("/usr/local/etc/BaseParamMap");
        if (newFile.exists()) {
            newFile.delete();
        }
        try {
            FileUtils.writeByteArrayToFile(newFile, file.getBytes());
            baseParamService.updateFromXml(newFile);
            ras.addFlashAttribute("error", baseParamService.getResult().getErrors());
        } catch (Exception e) {
            ras.addFlashAttribute("error",
                    "updateFromXml" + StringAdapter.getStackTraceException(e)/*e.getMessage()*/);
        }
        if (newFile.exists()) {
            newFile.delete();
        }
    }
    return "redirect:/BaseParam/show";
}