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.orchestra.portale.controller.UserEditController.java

@RequestMapping(value = "userEditProfile", method = RequestMethod.POST)
@Secured("ROLE_USER")
public ModelAndView updateUser(HttpServletRequest request, @ModelAttribute("SpringWeb") User user,
        MultipartFile avatar) {//from   w w  w  .  j av a 2  s. co  m
    ModelAndView model = new ModelAndView("userInfo");
    User olduser = pm.findUserByUsername(user.getUsername());
    user.setId(olduser.getId());

    if (user.getPassword() == null || user.getPassword().equals("")) {
        user.setPassword(olduser.getPassword());
    } else {
        user.setPassword(crypt(user.getPassword()));
    }

    pm.saveUser(user);

    if (avatar.getSize() > 0) {

        User user2 = pm.findUserByUsername(user.getUsername());
        MultipartFile file = avatar;

        try {
            byte[] bytes = file.getBytes();

            // Creating the directory to store file
            HttpSession session = request.getSession();
            ServletContext sc = session.getServletContext();

            File dir = new File(sc.getRealPath("/") + "dist" + File.separator + "user" + File.separator + "img"
                    + File.separator + user2.getId());
            if (!dir.exists()) {
                dir.mkdirs();
            }

            // Create the file on server
            File serverFile = new File(dir.getAbsolutePath() + File.separator + "avatar.jpg");
            BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(serverFile));
            stream.write(bytes);
            stream.close();
        } catch (Exception e) {

        }

    }
    model.addObject("user", user);
    HttpSession session = request.getSession();
    ServletContext sc = session.getServletContext();
    File dir = new File(sc.getRealPath("/") + "dist" + File.separator + "user" + File.separator + "img"
            + File.separator + user.getId() + File.separator + "avatar.jpg");
    if (dir.exists()) {
        model.addObject("avatar", "./dist/user/img/" + user.getId() + "/avatar.jpg");
    } else {
        model.addObject("avatar", "./dist/img/default_avatar.png");
    }
    return model;
}

From source file:de.science.hack.jetstream.web.controller.UploadController.java

/**
 * Upload a single file and process the content
 *
 * @param file the actual content// w  ww .  j  a  v  a 2 s .  c o m
 * @return the result as String
 */
@RequestMapping(value = "/upload", method = RequestMethod.POST)
public @ResponseBody ModelAndView upload(@RequestParam("file") MultipartFile file) {

    ModelAndView model;

    if (!file.isEmpty()) {
        try {
            byte[] bytes = file.getBytes();
            WindModelBuilder builder = new WindModelBuilder();
            TriangleMesh mesh = builder.build(bytes);
            resultCache.setMesh(mesh);

            model = new ModelAndView(WEBGL_VIEW);
        } catch (IOException e) {
            LOG.warn(e.getMessage(), e);
            model = new ModelAndView(FAILED_VIEW, MSG_OBJ, e.getMessage());
        }
    } else {
        model = new ModelAndView(FAILED_VIEW, MSG_OBJ, FAILED_UPLOAD);
    }

    return model;
}

From source file:org.opensafety.hishare.controller.UploadParcelController.java

@RequestMapping(value = "/file", method = RequestMethod.POST)
public ModelAndView handleFormUpload(@RequestParam("username") String username,
        @RequestParam("authenticationId") String authenticationId,
        @RequestParam("parcelName") String parcelName, @RequestParam("daysToLive") Integer daysToLive,
        @RequestParam("file") MultipartFile file) throws IOException {
    ModelAndView mav;/* ww  w.  j a v a2s .  com*/

    byte[] payload = null;

    if (!file.isEmpty()) {
        payload = file.getBytes();
    }

    mav = new ModelAndView("outputString");
    String[] accessInfo = uploadParcel.uploadParcel(username, authenticationId, parcelName, daysToLive,
            payload);
    String output = accessInfo[0] + ":" + accessInfo[1];
    mav.addObject("string", output);

    return mav;
}

From source file:dijalmasilva.controllers.ControladorIdolo.java

@RequestMapping("/new")
public String newIdolo(IdoloForm i, HttpServletRequest req, MultipartFile foto) throws IOException {
    Idolo idolo = convertToIdolo(i);/*  w  ww .jav a 2s.  c o  m*/

    if (foto.getSize() != 0) {
        idolo.setFoto(foto.getBytes());
    }

    Idolo newIdolo = serviceIdolo.salvar(idolo);

    if (newIdolo == null) {
        req.setAttribute("result", "No foi possvel cadastrar dolo.");
    } else {
        req.setAttribute("result", "?dolo cadastrado com sucesso.");
    }

    return "newGroup";
}

From source file:webcomicreader.webapp.controller.BackupRestoreController.java

@RequestMapping(value = "/uploadToDb", method = RequestMethod.POST)
public String uploadToDatabase(@RequestParam("file") MultipartFile file, Model model) throws IOException {
    boolean successful;
    if (!file.isEmpty()) {
        String fileStr = new String(file.getBytes(), "UTF-8");
        storage.reloaddb(fileStr);//  ww w . ja v  a  2s  .c  o  m
        successful = true;
    } else {
        successful = false;
    }
    model.addAttribute("successful", successful);
    return "loaddbResults";
}

From source file:org.openmrs.web.attribute.handler.LongFreeTextFileUploadHandler.java

/**
 * @see org.openmrs.web.attribute.handler.WebDatatypeHandler#getValue(org.openmrs.customdatatype.CustomDatatype, javax.servlet.http.HttpServletRequest, java.lang.String)
 *//*w  w w. j a  v a 2  s  .  com*/
@Override
public String getValue(LongFreeTextDatatype datatype, HttpServletRequest request, String formFieldName)
        throws InvalidCustomValueException {
    if (request instanceof MultipartRequest) {
        MultipartFile file = ((MultipartRequest) request).getFile(formFieldName);
        try {
            return new String(file.getBytes());
        } catch (IOException e) {
            throw new InvalidCustomValueException("Error handling file upload as a String", e);
        }
    } else {
        throw new IllegalArgumentException(
                "Programming error: file upload handler can only be used in a form with enctype='multipart/form-data'");
    }
}

From source file:org.pentaho.pat.server.servlet.FileUploadController.java

protected ModelAndView handle(final HttpServletRequest request, final HttpServletResponse response,
        final Object command, final BindException errors) throws Exception {
    final FileUploadBean fileUploadBean = (FileUploadBean) command;

    try {/*from  w  ww . j  a va2s .co m*/
        final MultipartFile files = fileUploadBean.getFile();
        String schemaData = new String(files.getBytes());
        String validationResult = AbstractSchemaValidator.validateAgainstXsd(schemaData);
        response.setContentType("text/plain"); //$NON-NLS-1$

        if (validationResult == null) {
            validationResult = ""; //$NON-NLS-1$
        }

        response.getWriter().print(VALIDATION_START + validationResult + VALIDATION_END);
        // Send a confirmation message to the client

        response.getWriter().print(DATA_START + (new String(Base64Coder.encode(files.getBytes()))) + DATA_END);
        response.setStatus(HttpServletResponse.SC_OK);
    } catch (Exception e) {
        LOG.error(e.getMessage());
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
    }

    // return the result to the client
    response.getWriter().flush();

    return null;
}

From source file:gerenciador.incubadora.controller.ArquivoController.java

@RequestMapping(value = "/imagem/upload/{id}", method = RequestMethod.POST)
public ModelAndView upload(@RequestParam("logo") MultipartFile file, @PathVariable Long id) throws IOException {
    ModelAndView mv;//from   w w w .  j  a  va  2  s  .  c o  m
    try {
        byte[] bytes = file.getBytes();
        Empreendimento empreendimento = new Empreendimento();
        empreendimento.setId(id);

        String logo = "C://imagens//empreendimento//" + id + " - " + file.getOriginalFilename();

        empreendimento.setLogo(logo);
        ServiceLocator.getEmpreendimentoService().uplaod(bytes, empreendimento);
        empreendimento = ServiceLocator.getEmpreendimentoService().readById(id);
        mv = new ModelAndView("redirect:/empreendimento");
        mv.addObject("empreendimento", empreendimento);
    } catch (Exception ex) {
        mv = new ModelAndView("error");
        mv.addObject("e", ex);
    }
    return mv;
}

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

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

    String r = "--- upload ---\n";
    try {/*www.j a  v a 2 s  .  c  o m*/
        if (!file.isEmpty()) {
            byte[] bytes = file.getBytes();

            r += "file uploaded\n";
            r += new String(bytes) + "\n";
        } else {
            r += "got empty file";
        }
    } catch (IOException | NullPointerException ex) {
        r += "--IOException|NullPointerException--\n" + ex + "\n";
    }
    return r + "---end---";
}

From source file:com.iisigroup.cap.sample.handler.SampleHandler.java

@HandlerType(HandlerTypeEnum.FileUpload)
public IResult upload(IRequest request) throws CapException {
    AjaxFormResult result = new AjaxFormResult();
    // String str = request.get("testStr");
    MultipartFile f = request.getFile("ufile");
    try {//from   w w  w.  j  a  v a 2s . c o  m
        FileUtils.writeByteArrayToFile(new File("xxxx.txt"), f.getBytes());
    } catch (IOException e) {
        logger.error(e.getMessage(), e);
    }
    String fileName = f.getOriginalFilename();
    result.set(Constants.AJAX_NOTIFY_MESSAGE, fileName + " upload file success!!");
    return result;
}