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.springsource.html5expense.controller.FileAttachmentController.java

@RequestMapping(value = "/save", method = RequestMethod.POST)
public String save(@RequestParam("file") MultipartFile file) {
    try {/*  w w  w.  j  a va  2  s.  co  m*/
        String fileName = file.getOriginalFilename();
        String contentType = file.getContentType();
        Attachment attachment = new Attachment(fileName, contentType, file.getBytes());
        attachmentService.save(attachment);
    } catch (IOException e) {
        e.printStackTrace();
    }
    return "redirect:/";
}

From source file:com.hillert.botanic.controller.UploadController.java

/**
 * Handles image file uplods. Images are persistence to the database using
 * {@link ImageRepository}./*from w w w .j  a v  a 2s.  co  m*/
 *
 * @param file Must not be null
 * @param plantId Must not be null
 * @return The saved {@link Image} or {@code NULL} in case of a problem.
 */
@RequestMapping(method = RequestMethod.POST)
public Image handleFileUpload(@RequestParam("file") MultipartFile file, @PathVariable("plantId") Long plantId) {

    if (file.isEmpty()) {
        return null;
    }

    byte[] bytes;

    try {
        bytes = file.getBytes();
    } catch (IOException e) {
        throw new IllegalStateException("Error uploading file.", e);
    }

    Plant plant = plantRepository.findOne(plantId);

    if (plant == null) {
        throw new IllegalStateException(String.format("Plant with id '%s' not found.", plantId));
    }

    Image image = new Image();
    image.setImage(bytes);
    image.setPlant(plant);
    image.setName(file.getOriginalFilename());
    Image savedImage = imageRepository.save(image);

    Image imageToReturn = new Image();
    imageToReturn.setId(savedImage.getId());
    imageToReturn.setImage(savedImage.getImage());
    imageToReturn.setName(savedImage.getName());

    return imageToReturn;
}

From source file:com.cami.web.controller.uploadController.java

@RequestMapping(value = "/upload", method = RequestMethod.POST)
public @ResponseBody String upload(MultipartHttpServletRequest request, HttpServletResponse response) {

    //0. notice, we have used MultipartHttpServletRequest

    //1. get the files from the request object
    Iterator<String> itr = request.getFileNames();

    MultipartFile mpf = request.getFile(itr.next());
    System.out.println(mpf.getOriginalFilename() + " uploaded!");

    try {/*from w w  w .  j a v a2  s. c om*/
        //just temporary save file info into ufile
        ufile.length = mpf.getBytes().length;
        ufile.bytes = mpf.getBytes();
        ufile.type = mpf.getContentType();
        ufile.name = mpf.getOriginalFilename();

    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    //2. send it back to the client as <img> that calls get method
    //we are using getTimeInMillis to avoid server cached image 

    return "<img src='" + request.getContextPath() + "/upload/get/" + Calendar.getInstance().getTimeInMillis()
            + "' />";

}

From source file:com.xiovr.unibot.web.controller.ManageController.java

@RequestMapping(value = "/bot/uploadscript", method = RequestMethod.POST)
public @ResponseBody String scriptFileUpload(@RequestParam("name") String name,
        @RequestParam("file") MultipartFile file) {
    if (!file.isEmpty()) {
        try {/*from  w w w . jav a 2  s. c o  m*/
            byte[] bytes = file.getBytes();
            BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(new File(
                    botGameConfig.getAbsDirPath() + "/" + botEnvironment.getScriptsPathPrefix() + "/" + name)));
            stream.write(bytes);
            stream.close();
            return "You successfully uploaded " + name + " into " + name + "-uploaded !";
        } 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:com.xiovr.unibot.web.controller.ManageController.java

@RequestMapping(value = "/env/uploadcryptor", method = RequestMethod.POST)
public @ResponseBody String cryptoreFileUpload(@RequestParam("name") String name,
        @RequestParam("file") MultipartFile file) {
    if (!file.isEmpty()) {
        try {//  ww w .ja  v a  2 s  .  co m
            byte[] bytes = file.getBytes();
            BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(
                    new File(botGameConfig.getAbsDirPath() + "/" + BotEnvironment.LIBS_PATH + "/" + name)));
            stream.write(bytes);
            stream.close();
            return "You successfully uploaded " + name + " into " + name + "-uploaded !";
        } 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:mx.com.quadrum.service.impl.TipoContratoServiceImpl.java

@Override
public String agregar(TipoContrato tipoContrato, MultipartFile formato) {

    if (!formato.isEmpty()) {
        String path = FORMATOS + tipoContrato.getNombre() + ".jasper";
        try {//from w ww.  jav a2  s  .  co  m
            if (crearArchivoContenido(path, formato.getBytes())) {
                if (tipoContratoRepository.agregar(tipoContrato)) {
                    File file = new File(path);
                    file.renameTo(new File(FORMATOS + tipoContrato.getId() + ".jasper"));
                    return ADD_CORRECT + TIPO_CONTRATO;
                }
                return ERROR_HIBERNATE;
            } else {
                return "Ups!...#No fue posible guardar el formato, intente mas tarde.";
            }
        } catch (IOException ex) {
            Logger.getLogger(TipoContratoServiceImpl.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    return "Ups!...#Encontramos que el archivo que subio esta vacio.";

}

From source file:com.jayway.restassured.examples.springmvc.controller.FileUploadController.java

@RequestMapping(value = "/fileUploadWithParam", method = POST, consumes = MULTIPART_FORM_DATA_VALUE, produces = APPLICATION_JSON_VALUE)
public @ResponseBody FileWithParam fileUploadWithParam(@RequestParam(value = "controlName") MultipartFile file,
        @RequestParam(value = "param", required = false) String param) throws IOException {
    FileDescription fd1 = new FileDescription();
    fd1.setContent(new String(file.getBytes()));
    fd1.setName(file.getName());//from w ww  .  j a va  2s .  c o  m
    fd1.setMimeType(file.getContentType());
    fd1.setOriginalName(file.getOriginalFilename());
    fd1.setSize(file.getSize());

    FileWithParam fileWithParam = new FileWithParam();
    fileWithParam.setFile(fd1);
    fileWithParam.setParam(param);

    return fileWithParam;
}

From source file:com.jayway.restassured.examples.springmvc.controller.FileUploadController.java

@RequestMapping(value = "/multiFileUpload", method = POST, consumes = MULTIPART_FORM_DATA_VALUE, produces = APPLICATION_JSON_VALUE)
public @ResponseBody List<FileDescription> multiFileUpload(
        @RequestParam(value = "controlName1") MultipartFile file1,
        @RequestParam(value = "controlName2") MultipartFile file2) throws IOException {
    FileDescription fd1 = new FileDescription();
    fd1.setContent(new String(file1.getBytes()));
    fd1.setName(file1.getName());/* w  ww  .  j a v a  2 s . c  o m*/
    fd1.setMimeType(file1.getContentType());
    fd1.setOriginalName(file1.getOriginalFilename());
    fd1.setSize(file1.getSize());

    FileDescription fd2 = new FileDescription();
    fd2.setContent(new String(file2.getBytes()));
    fd2.setName(file2.getName());
    fd2.setMimeType(file2.getContentType());
    fd2.setOriginalName(file2.getOriginalFilename());
    fd2.setSize(file2.getSize());
    return asList(fd1, fd2);
}

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

@RequestMapping(value = "/addProduct", method = RequestMethod.POST)
public String addProduct(@Valid Product product, BindingResult result, RedirectAttributes re,
        @RequestParam("file") MultipartFile file) {
    String view = "redirect:/products";
    if (!result.hasErrors()) {
        try {// w w  w.  j a  va2  s  .c  o  m
            product.setImage(file.getBytes());
            product.setStatus("ACTIVE");
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        productService.addProduct(product);
    } else {
        //System.out.println("inside error adding product");
        view = "addProduct";
    }
    return view;
}

From source file:com.br.helpdesk.controller.AttachmentsController.java

/**
 * upload//from w ww  . j ava2s.co m
 */
@RequestMapping(method = RequestMethod.POST)
@ResponseBody
public String uploadFile(HttpServletRequest request, HttpServletResponse response) throws Exception {
    String username = request.getParameter("username");
    MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
    Collection<MultipartFile> filesCollection = multipartRequest.getFileMap().values();
    try {
        for (MultipartFile multipartFile : filesCollection) {
            String fileName = "##" + username + "##" + multipartFile.getOriginalFilename();
            attachmentsService.createFile(fileName, multipartFile.getBytes());
        }
    } catch (IOException e) {
        return "{success: false}";
    }
    return "{success: true}";
}