Example usage for org.springframework.web.multipart.commons CommonsMultipartFile getBytes

List of usage examples for org.springframework.web.multipart.commons CommonsMultipartFile getBytes

Introduction

In this page you can find the example usage for org.springframework.web.multipart.commons CommonsMultipartFile getBytes.

Prototype

@Override
    public byte[] getBytes() 

Source Link

Usage

From source file:org.easit.core.controllers.facebook.FacebookPhotosController.java

private Resource getUploadResource(final String filename, CommonsMultipartFile content) {
    Resource a = new ByteArrayResource(content.getBytes()) {
        public String getFilename() throws IllegalStateException {
            return filename;
        };/*from  www .  j  a  v a2s  .c o m*/
    };
    return a;
}

From source file:org.openmrs.module.report.web.controller.report.ReportTypeController.java

@RequestMapping(method = RequestMethod.POST)
public String onSubmit(@ModelAttribute("reportType") BirtReportType reportType, BindingResult bindingResult,
        HttpServletRequest request, SessionStatus status) {
    new BirtReportTypeValidator().validate(reportType, bindingResult);
    if (bindingResult.hasErrors()) {
        return "/module/report/report/reportType";
    } else {/* w w  w . j a  va2s  . c o  m*/
        BirtReportService birtReportService = Context.getService(BirtReportService.class);
        BirtReportConfig config = ReportConstants.getConfig();
        String tempPath = config.getRealPath();
        if (StringUtils.isBlank(tempPath)) {
            Throwable th = new Throwable("Not exist realpath for save file report!");

        }
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        CommonsMultipartFile file = (CommonsMultipartFile) multipartRequest.getFile("reportFile");
        if (file != null && file.getBytes() != null && file.isEmpty() == false) {
            long temp = new Date().getTime();
            //String nameReport = org.openmrs.module.report.util.StringUtils.replaceSpecialWithUnderLineCharacter(reportType.getBirtReport().getName());
            //String nameReportType = org.openmrs.module.report.util.StringUtils.replaceSpecialWithUnderLineCharacter(reportType.getName());
            String fileName = reportType.getBirtReport().getId() + "_" + temp + ".rptdesign";
            String reportFilename = tempPath + "/" + fileName;
            reportFilename = reportFilename.replaceAll("//", "/");

            try {
                FileCopyUtils.copy(file.getInputStream(), new FileOutputStream(reportFilename));
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            reportType.setPath(fileName);
        } else if (reportType.getId() != null && reportType.getId().intValue() > 0) {
            reportType.setPath(birtReportService.getBirtReportTypeById(reportType.getId()).getPath());
        }

        reportType.setCreatedBy(Context.getAuthenticatedUser().getGivenName());
        reportType.setCreatedOn(new Date());
        birtReportService.saveBirtReportType(reportType);
        status.setComplete();
        return "redirect:/module/report/reportType.form?reportId=" + reportType.getBirtReport().getId();
    }
}

From source file:com.mycompany.capstone.controllers.ImageController.java

@RequestMapping(value = "/doUpload", method = RequestMethod.POST)
public String handleFileUpload(@RequestParam(value = "userfile") CommonsMultipartFile[] fileUpload, Map model) {

    if (fileUpload != null && fileUpload.length > 0) {
        for (CommonsMultipartFile aFile : fileUpload) {

            System.out.println("Saving file: " + aFile.getOriginalFilename());

            Image uploadFile = new Image();
            uploadFile.setImagePath(aFile.getOriginalFilename());
            uploadFile.setImageData(aFile.getBytes());
            adminPageImageDao.create(uploadFile);

            model.put("uploadFile", uploadFile);

        }//w  w  w  .j  av  a 2s.c o m
    }

    return "upload_result";
}

From source file:com.autoupdater.server.services.FileServiceImp.java

@Override
public synchronized String saveMultipartFile(CommonsMultipartFile multipartFile) throws IOException {
    logger.debug("Attempting to save MultipartFile: " + multipartFile.getName());
    String storagePath = createStoragePath();
    saveFile(getStorageDirectory() + storagePath, multipartFile.getBytes());
    logger.debug("Saved MultipartFile: " + multipartFile.getName());
    return storagePath;
}

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

@RequestMapping(value = "/doUpload", method = RequestMethod.POST)
public String handleFileUpload(HttpServletRequest request, @RequestParam CommonsMultipartFile[] fileUpload)
        throws Exception {

    if (fileUpload != null && fileUpload.length > 0) {
        for (CommonsMultipartFile aFile : fileUpload) {
            String fileName = null;
            if (!aFile.isEmpty()) {
                try {
                    fileName = aFile.getOriginalFilename();
                    byte[] bytes = aFile.getBytes();
                    BufferedOutputStream buffStream = new BufferedOutputStream(
                            new FileOutputStream(new File("D:/CX1/" + fileName)));
                    buffStream.write(bytes);
                    buffStream.close();/*ww  w  . j a  v a 2  s.co  m*/
                    System.out.println("You have successfully uploaded " + fileName);
                } catch (Exception e) {
                    System.out.println("You failed to upload " + fileName + ": " + e.getMessage());
                }
            } else {
                System.out.println("Unable to upload. File is empty.");
            }

            System.out.println("Saving file: " + aFile.getOriginalFilename());

            aFile.getOriginalFilename();
            aFile.getBytes();

        }
    }

    return "admin";
}

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

@RequestMapping(value = "/asyncUpload", method = RequestMethod.POST/*, produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.MULTIPART_FORM_DATA_VALUE*/)
@ResponseBody//from w w w  .ja va  2 s .c  o  m
public ResponseEntity<String> asyncFileUpload(HttpServletRequest request,
        @RequestParam CommonsMultipartFile[] fileUpload) throws Exception {

    if (fileUpload != null && fileUpload.length > 0) {
        for (CommonsMultipartFile aFile : fileUpload) {
            String fileName = null;
            if (!aFile.isEmpty()) {
                try {
                    fileName = aFile.getOriginalFilename();
                    byte[] bytes = aFile.getBytes();
                    BufferedOutputStream buffStream = new BufferedOutputStream(
                            new FileOutputStream(new File("D:/CX1/" + fileName)));
                    buffStream.write(bytes);
                    buffStream.close();
                    System.out.println("You have successfully uploaded " + fileName);
                } catch (Exception e) {
                    System.out.println("You failed to upload " + fileName + ": " + e.getMessage());
                }
            } else {
                System.out.println("Unable to upload. File is empty.");
            }

            System.out.println("Saving file: " + aFile.getOriginalFilename());

            aFile.getOriginalFilename();
            aFile.getBytes();

        }
    }

    return new ResponseEntity<>("success", HttpStatus.OK);
}

From source file:com.hp.avmon.agentless.service.AgentlessService.java

public String importAgentlessFile(HttpServletRequest request) throws IOException {

    String result = StringUtil.EMPTY;
    HashMap<String, ArrayList<Map<String, String>>> resultMap = new HashMap<String, ArrayList<Map<String, String>>>();
    ArrayList<Map<String, String>> files = new ArrayList<Map<String, String>>();
    Map<String, HashMap<String, List<String>>> map = new HashMap<String, HashMap<String, List<String>>>();

    MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
    //?//from   w w  w . jav  a 2 s .  c o m
    String templatePath = Config.getInstance().getAgentlessfilesUploadPath();
    File dirPath = new File(templatePath);
    if (!dirPath.exists()) {
        dirPath.mkdirs();
    }
    Map<String, String> fileMap;
    try {
        for (Iterator it = multipartRequest.getFileNames(); it.hasNext();) {
            String fileName = (String) it.next();
            CommonsMultipartFile file = (CommonsMultipartFile) multipartRequest.getFile(fileName);
            if (file != null && file.getSize() != 0) {
                String sep = System.getProperty("file.separator");
                String importFilePath = dirPath + sep + file.getOriginalFilename();
                File uploadedFile = new File(importFilePath);
                FileCopyUtils.copy(file.getBytes(), uploadedFile);
                //??
                String importStatus = importRmpInstance(importFilePath);
                //boolean importStatus = false;
                String name = file.getOriginalFilename();
                fileMap = new HashMap<String, String>();

                if (importStatus.indexOf("success") > -1) {
                    fileMap.put("status", "success");
                    String[] s = importStatus.split(":");
                    fileMap.put("msg", "?" + s[1] + "" + s[2]);
                } else {
                    fileMap.put("status", "failed");
                    fileMap.put("msg", importStatus);
                }
                fileMap.put("url", "");
                fileMap.put("thumbnailUrl", "");
                fileMap.put("name", name);
                fileMap.put("type", "image/jpeg");
                fileMap.put("size", file.getSize() + "");
                fileMap.put("deleteUrl", "");
                fileMap.put("deleteType", "DELETE");
                files.add(fileMap);
            }
        }

    } catch (Exception e) {
        e.printStackTrace();
        logger.error(e);
    }
    resultMap.put("files", files);
    result = JackJson.fromObjectToJson(resultMap);
    logger.debug(result);
    return result;
}

From source file:com.lenovo.h2000.mvc.LicenseController.java

@RequestMapping(value = "/import", method = RequestMethod.POST)
@ResponseBody//from ww w .j  a va  2s . c o  m
public String upload(@RequestParam("licenseFile") CommonsMultipartFile file, @RequestHeader HttpHeaders headers)
        throws Exception {
    _logger.info("getting LicenseController.upload headers.X-Lenovo-ClusterName "
            + headers.getFirst("X-Lenovo-ClusterName"));
    Map<String, String> header = new HashMap<String, String>();
    header.put("X-Lenovo-ClusterName", headers.getFirst("X-Lenovo-ClusterName"));
    /*String path = System.getProperty("java.io.tmpdir")+ "/" + new Date().getTime()+file.getOriginalFilename();
    File newFile=new File(path);
      file.transferTo(newFile);
              
      return _licenseService.upload(path, header);*/
    return _licenseService.upload(file.getBytes(), header);
}

From source file:com.br.uepb.controller.MedicaoController.java

@RequestMapping(value = "/home/medicao.html", method = RequestMethod.POST)
public ModelAndView medicaoPost(HttpServletRequest request, Model model,
        @ModelAttribute("uploadItem") UploadItem uploadItem) {

    String login = request.getSession().getAttribute("login").toString();

    SessaoBusiness sessao = GerenciarSessaoBusiness.getSessaoBusiness(login);
    MedicoesBusiness medicoesBusiness = new MedicoesBusiness();
    LoginDomain loginDomain = sessao.getLoginDomain();

    ModelAndView modelAndView = new ModelAndView();
    String mensagem = "";
    String status = "";

    @SuppressWarnings("deprecation")
    String uploadRootPath = request.getRealPath(File.separator);

    File uploadRootDir = new File(uploadRootPath);

    // Cria o diretrio se no existir
    if (!uploadRootDir.exists()) {
        uploadRootDir.mkdirs();/*from www  .jav  a  2  s  . co m*/
    }
    CommonsMultipartFile fileData = uploadItem.getFileData();

    // Nome do arquivo cliente
    String name = fileData.getOriginalFilename();

    if (name != null && name.length() > 0) {
        try {
            // Create the file on server
            File serverFile = new File(uploadRootDir.getAbsolutePath() + File.separator + name);

            BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(serverFile));
            stream.write(fileData.getBytes());
            stream.close();
            // Salvou o arquivo xml

            String tipo_dispositivo = uploadItem.getTipo_dispositivo();
            String arquivo = serverFile.toString();

            if (tipo_dispositivo.equals("2")) { // oximetro
                modelAndView.addObject("tipoDispositivo", 2);
                if (medicoesBusiness.medicaoOximetro(arquivo, login)) {
                    //medicoesBusiness.medicaoOximetro(arquivo);
                    mensagem = "Medio Oximetro cadastrada com sucesso!";
                    status = "0";

                    MedicaoOximetroDomain oximetro = medicoesBusiness
                            .listaUltimaMedicaoOximetro(loginDomain.getPaciente().getId());
                    modelAndView.addObject("oximetro", oximetro);
                    modelAndView.addObject("balanca", null);
                    modelAndView.addObject("pressao", null);
                    modelAndView.addObject("icg", null);

                } else {
                    mensagem = "Erro ao cadastrar Oximetro arquivo XML!";
                    status = "1";
                }

            } else if (tipo_dispositivo.equals("1")) { // balanca
                modelAndView.addObject("tipoDispositivo", 1);
                if (medicoesBusiness.medicaoBalanca(arquivo, login)) {
                    mensagem = "Medio Balana cadastrada com sucesso!";
                    status = "0";

                    MedicaoBalancaDomain balanca = medicoesBusiness
                            .listaUltimaMedicaoBalanca(loginDomain.getPaciente().getId());
                    modelAndView.addObject("oximetro", null);
                    modelAndView.addObject("balanca", balanca);
                    modelAndView.addObject("pressao", null);
                    modelAndView.addObject("icg", null);
                } else {
                    mensagem = "Erro ao cadastrar Balana arquivo XML!";
                    status = "1";
                }

            } else if (tipo_dispositivo.equals("3")) { // pressao
                modelAndView.addObject("tipoDispositivo", 3);
                if (medicoesBusiness.medicaoPressao(arquivo, login)) {
                    mensagem = "Medio Presso cadastrada com sucesso!";
                    status = "0";

                    MedicaoPressaoDomain pressao = medicoesBusiness
                            .listaUltimaMedicaoPressao(loginDomain.getPaciente().getId());
                    modelAndView.addObject("oximetro", null);
                    modelAndView.addObject("balanca", null);
                    modelAndView.addObject("pressao", pressao);
                    modelAndView.addObject("icg", null);
                } else {
                    mensagem = "Erro ao cadastrar Presso arquivo XML!";
                    status = "1";
                }

            } else if (tipo_dispositivo.equals("0")) { // icg
                modelAndView.addObject("tipoDispositivo", 0);
                if (medicoesBusiness.medicaoIcg(arquivo, login)) {
                    mensagem = "Medio ICG cadastrada com sucesso!";
                    status = "0";

                    MedicaoIcgDomain icg = medicoesBusiness
                            .listaUltimaMedicaoIcg(loginDomain.getPaciente().getId());
                    modelAndView.addObject("oximetro", null);
                    modelAndView.addObject("balanca", null);
                    modelAndView.addObject("pressao", null);
                    modelAndView.addObject("icg", icg);

                } else {
                    mensagem = "Erro ao cadastrar ICG arquivo XML!";
                    status = "1";
                }
            } else {
                mensagem = "Erro ao cadastrar arquivo XML!";
                status = "1";
            }

        } catch (Exception e) {
            mensagem = "Erro ao cadastrar arquivo XML!";
            status = "1";
        }
    } else {
        mensagem = "O arquivo no foi informado ou est vazio";
        status = "1";
    }

    if (status == "1") {
        modelAndView.addObject("tipoDispositivo", null);
        modelAndView.addObject("oximetro", null);
        modelAndView.addObject("balanca", null);
        modelAndView.addObject("pressao", null);
        modelAndView.addObject("icg", null);
    }

    model.addAttribute("mensagem", mensagem);
    model.addAttribute("status", status);
    modelAndView.setViewName("home/medicao");
    return modelAndView;
}

From source file:com.digitalizat.control.TdocController.java

@RequestMapping(value = "guardarFichero", method = RequestMethod.POST)
public String guardarFichero(@RequestParam(value = "file", required = true) CommonsMultipartFile file,
        @RequestParam(value = "idFolder", required = true) Integer idFolder, HttpServletRequest request,
        Model m) throws FileNotFoundException, IOException, Exception {
    HttpSession sesion = request.getSession();
    User usuarioLogado;// www. j a v a  2  s.c o m
    if (sesion.getAttribute("user") == null && (!(Boolean) sesion.getAttribute("logged"))) {
        throw new Exception("Login requerido");
    } else {
        usuarioLogado = (User) sesion.getAttribute("user");
    }
    File localFile = new File(serverProperties.getRutaGestorDocumental() + file.getOriginalFilename());
    FileOutputStream os;
    os = new FileOutputStream(localFile);
    os.write(file.getBytes());

    Document doc = new Document();
    doc.setBasePath(serverProperties.getRutaGestorDocumental());
    doc.setPathdoc("/" + usuarioLogado.getBranch().getId() + "/");
    doc.setBranch(usuarioLogado.getBranch());
    doc.setFileName(file.getOriginalFilename());
    if (idFolder != null && !idFolder.equals(new Integer(0))) {
        doc.setParent(tdocManager.getDocument(idFolder));
    }
    doc.setFolder(Boolean.FALSE);
    tdocManager.addDocument(doc);
    return "index.html#/tdoc";
}