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:ch.silviowangler.dox.web.ImportController.java

@SuppressWarnings("unchecked")
@RequestMapping(method = RequestMethod.POST, value = "performImport.html")
public ResponseEntity<String> importDocument(MultipartFile file, WebRequest request,
        @RequestParam("x_client") String client) {

    try {/*www.j a  va2  s.c  o m*/
        DocumentClass documentClass = new DocumentClass(request.getParameter(DOCUMENT_CLASS_SHORT_NAME));

        Iterator<String> params = request.getParameterNames();
        Map<TranslatableKey, DescriptiveIndex> indices = newHashMap();

        while (params.hasNext()) {
            String param = params.next();
            if (!DOCUMENT_CLASS_SHORT_NAME.endsWith(param) && !param.startsWith("x_")) {
                indices.put(new TranslatableKey(param), new DescriptiveIndex(
                        new String(request.getParameter(param).getBytes("iso-8859-1"), "utf-8")));
            }
        }

        PhysicalDocument physicalDocument = new PhysicalDocument(documentClass, file.getBytes(), indices,
                file.getOriginalFilename());
        physicalDocument.setClient(client);

        DocumentReference documentReference = documentService.importDocument(physicalDocument);

        logger.info("Successfully imported file {}. Id = {}", file.getOriginalFilename(),
                documentReference.getHash());
        return new ResponseEntity(CREATED);

    } catch (ValidationException | IOException | DocumentClassNotFoundException e) {
        logger.error("Unable to import document", e);
        return new ResponseEntity(e.getMessage(), CONFLICT);
    } catch (DocumentDuplicationException e) {
        logger.error("Unable to import document. Duplicate document detected", e);
        return new ResponseEntity(e.getMessage(), CONFLICT);
    }
}

From source file:eu.trentorise.smartcampus.feedback.controller.FeedbackController.java

/**
 * Upload feedback data. Take as input {@link Feedback} instance as JSON String passed 
 * in 'body' param and the {@link MultipartFile} file param for the (optional) screenshot data.
 * @param request/*ww  w  .  j av a  2 s .c o  m*/
 * @param response
 * @param body
 * @param file
 * @return
 */
@RequestMapping(value = "/feedback", method = RequestMethod.POST)
public @ResponseBody String feedback(HttpServletRequest request, HttpServletResponse response,
        @RequestParam("body") String body, @RequestParam(required = false, value = "file") MultipartFile file) {
    User user = null;
    try {
        user = retrieveUser(request, response);
    } catch (AcServiceException e) {
        logger.error("Error reading the user: " + e.getMessage());
    }
    if (user == null) {
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        return null;
    }

    try {
        Feedback feedback = mapper.readValue(body, Feedback.class);
        if (feedback == null) {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            return null;
        }
        feedback.setCreatorId("" + user.getId());
        feedback.setUser(feedback.getCreatorId());

        if (file != null) {
            String fileId = feedbackFileManager.storeFile(file.getBytes());
            feedback.setFileId(fileId);
        }
        feedback = feedbackManager.storeFeedback(feedback);
        return feedback.getId();
    } catch (Exception e) {
        logger.error("Error storing feedback: " + e.getMessage());
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return null;
    }
}

From source file:com.ineunet.knife.upload.controller.UploadController.java

@RequestMapping(value = "doUpload", method = RequestMethod.POST)
public @ResponseBody String doUpload(HttpServletRequest request, @RequestParam(value = "field") String field)
        throws IOException {
    MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
    Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
    WebPaths.init(request);/*from  w w w  . ja  v a  2  s .  co  m*/
    String rootPath = WebPaths.getRootPath();
    String column = ClassStrUtils.hump2Underline(field);

    // If associatedId is null or 0, generate one.
    Long associatedId = this.getService().validateId(column, null);
    String fileName = "";
    for (Map.Entry<String, MultipartFile> uf : fileMap.entrySet()) {
        MultipartFile mf = uf.getValue();
        String originalName = mf.getOriginalFilename();
        this.getService().setOriginalFileName(column, associatedId, originalName);
        if (!UploadUtils.checkFileType(originalName)) {
            throw new RuntimeException("unsupported file type");
        }

        fileName = UploadUtils.buildTempFileName(this.getService().tableName(), column, associatedId,
                originalName);
        String key = this.getService().getKey(column, associatedId);
        this.getService().setTempFileName(key, fileName);

        // copy file
        String tempPath = rootPath + UploadUtils.TEMP_PATH_PART;
        File file = new File(tempPath + fileName);
        FileCopyUtils.copy(mf.getBytes(), file);

        this.getService().setTempContent(mf.getBytes(), column, associatedId);
        break;
    }
    return fileName;
}

From source file:ch.ledcom.jpreseed.web.JPreseedController.java

@RequestMapping(value = "/", method = RequestMethod.POST, produces = GZIP)
public void createUsbImage(@RequestParam("distro") String distro, @RequestParam("version") String version,
        @RequestParam("preseeds") List<MultipartFile> preseeds,
        @RequestParam("syslinux") MultipartFile syslinux, HttpServletResponse response, OutputStream out)
        throws IOException {

    URI imageUri = distroService.getDistributionByName(distro).getVersionByShortName(version).getUsbImageUri();

    try (TemporaryPreseedStore preseedStore = new TemporaryPreseedStore();
            Downloader srcBootImgGz = downloaderFactory.getDownloader(imageUri);
            GZIPOutputStream targetBootImgGz = new GZIPOutputStream(out)) {

        logger.debug("Storing preseeds...");
        preseedStore.addPreseeds(preseeds);

        logger.debug("Preparing response...");
        response.setHeader(CONTENT_DISPOSITION, "attachment; filename=\"boot.img.gz\"");

        logger.debug("Creating USB image ...");
        usbCreator.create(srcBootImgGz.getContent(), targetBootImgGz, wrap(syslinux.getBytes()),
                preseedStore.getPreseeds());
        logger.debug("USB image created.");
    }/*ww w.  j  ava  2s.co  m*/
}

From source file:org.openmrs.module.drawing.web.controller.ManageTemplatesController.java

@RequestMapping(value = "/module/drawing/manageTemplates", method = RequestMethod.POST)
public void manage(@RequestParam(value = "templateName", required = false) String templateName,
        @RequestParam(value = "template", required = true) MultipartFile file, ModelMap model,
        HttpSession session) {//from   w ww  .ja v a 2 s . c om

    model.addAttribute("encodedTemplateNames", DrawingUtil.getAllTemplateNames());
    if (file == null || file.getSize() == 0) {
        session.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "Please Fill All The Fields");
        return;
    } else if (!DrawingUtil.isImage(file.getOriginalFilename())) {
        session.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "File Format Not Supported");
        return;
    }
    if (StringUtils.isBlank(templateName))
        templateName = file.getOriginalFilename();
    else
        templateName = templateName + "." + DrawingUtil.getExtension(file.getOriginalFilename());

    try {
        BufferedImage bi = ImageIO.read(new ByteArrayInputStream(file.getBytes()));
        Boolean saved = DrawingUtil.saveFile(templateName, bi);
        if (saved) {
            session.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "Template Saved");
            model.addAttribute("encodedTemplateNames", DrawingUtil.getAllTemplateNames());

        } else
            session.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "Error Saving Template");

    } catch (IOException e) {
        session.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "Unable To Save Uploaded File");
        log.error("Unable to read uploadedFile", e);
    }

}

From source file:net.duckling.ddl.web.sync.FileContentController.java

@RequestMapping(value = "/upload_session/append", method = RequestMethod.POST)
public void appendUploadSession(HttpServletRequest request, HttpServletResponse response,
        @RequestParam("session_id") String sessionId, @RequestParam("chunk_index") Integer chunkIndex,
        @RequestParam("chunk_data") MultipartFile chunkData) {
    ChunkUploadSession chunkUploadSession = chunkUploadSessionService.get(sessionId);
    if (chunkUploadSession == null) {
        JsonResponse.chunkUploadSessionNotFound(response, sessionId);
        return;/*w  w  w . ja v a 2  s  .  co m*/
    }

    ChunkResponse chunkResponse = null;
    try {
        chunkResponse = fileStorage.executeChunkUpload(chunkUploadSession.getClbId().intValue(), chunkIndex,
                chunkData.getBytes(), (int) chunkData.getSize());
    } catch (IOException e) {
        JsonResponse.error(response);
        LOG.error(String.format("Fail to upload chunk %d of clbid %d.", chunkIndex,
                chunkUploadSession.getClbId()), e);
        return;
    }

    if (chunkResponse.isSccuessStatus()) {
        JsonResponse.ackChunk(response, sessionId, "ack", chunkResponse.getEmptyChunkSet());
    } else if (chunkResponse.isDuplicateChunk()) {
        JsonResponse.ackChunk(response, sessionId, "duplicated", chunkResponse.getEmptyChunkSet());
    } else if (chunkResponse.getStatusCode() == ChunkResponse.CHUNK_INDEX_INVALID) {
        JsonResponse.ackChunk(response, sessionId, "invalid_index", null);
    } else if (chunkResponse.getStatusCode() == ChunkResponse.EXCEED_MAX_CHUNK_SIZE) {
        JsonResponse.error(response);
    } else {
        JsonResponse.error(response);
    }
}

From source file:mx.edu.um.mateo.inventario.web.ProductoController.java

@RequestMapping(value = "/crea", method = RequestMethod.POST)
public String crea(HttpServletRequest request, @Valid Producto producto, BindingResult bindingResult,
        Errors errors, Model modelo, RedirectAttributes redirectAttributes,
        @RequestParam(value = "imagen", required = false) MultipartFile archivo) {
    for (String nombre : request.getParameterMap().keySet()) {
        log.debug("Param: {} : {}", nombre, request.getParameterMap().get(nombre));
    }//  w w  w .j  a  v a2  s .  c om
    if (bindingResult.hasErrors()) {
        log.debug("Hubo algun error en la forma, regresando");
        return "inventario/producto/nuevo";
    }

    try {

        if (archivo != null && !archivo.isEmpty()) {
            Imagen imagen = new Imagen(archivo.getOriginalFilename(), archivo.getContentType(),
                    archivo.getSize(), archivo.getBytes());
            producto.getImagenes().add(imagen);
        }
        Usuario usuario = ambiente.obtieneUsuario();
        producto = productoDao.crea(producto, usuario);

    } catch (ConstraintViolationException e) {
        log.error("No se pudo crear el producto", e);
        errors.rejectValue("nombre", "campo.duplicado.message", new String[] { "nombre" }, null);

        Map<String, Object> params = new HashMap<>();
        params.put("almacen", request.getSession().getAttribute("almacenId"));
        params.put("reporte", true);
        params = tipoProductoDao.lista(params);
        modelo.addAttribute("tiposDeProducto", params.get("tiposDeProducto"));

        return "inventario/producto/nuevo";
    } catch (IOException e) {
        log.error("No se pudo crear el producto", e);
        errors.rejectValue("imagenes", "problema.con.imagen.message",
                new String[] { archivo.getOriginalFilename() }, null);

        Map<String, Object> params = new HashMap<>();
        params.put("almacen", request.getSession().getAttribute("almacenId"));
        params.put("reporte", true);
        params = tipoProductoDao.lista(params);
        modelo.addAttribute("tiposDeProducto", params.get("tiposDeProducto"));

        return "inventario/producto/nuevo";
    }

    redirectAttributes.addFlashAttribute("message", "producto.creado.message");
    redirectAttributes.addFlashAttribute("messageAttrs", new String[] { producto.getNombre() });

    return "redirect:/inventario/producto/ver/" + producto.getId();
}

From source file:com.springsource.html5expense.controller.ExpenseController.java

@RequestMapping(value = "/createNewExpenseReport", method = RequestMethod.POST)
public String createNewExpenseReport(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
    String description = request.getParameter("description");
    String expenseTypeVal = request.getParameter("expenseTypeId");
    ExpenseType expenseType = expenseTypeService.getExpenseTypeById(new Long(expenseTypeVal));
    String amount = request.getParameter("amount");
    Date expenseDate = new Date();
    Double amountVal = new Double(amount);
    User user = (User) request.getSession().getAttribute("user");
    String fileName = "";
    String contentType = "";
    if (file != null) {
        try {//from w  ww  .  j av  a 2  s.c o m
            fileName = file.getOriginalFilename();
            contentType = file.getContentType();
            Attachment attachment = new Attachment(fileName, contentType, file.getBytes());
            attachmentService.save(attachment);
            Long id = expenseService.createExpense(description, expenseType, expenseDate, amountVal, user,
                    attachment);
        } catch (Exception e) {

        }
    }

    return "redirect:/";
}

From source file:org.jasig.portlet.cms.controller.EditPostController.java

private void processPostAttachments(final ActionRequest request, final Post post) throws Exception {
    if (FileUploadBase.isMultipartContent(new PortletRequestContext(request))) {

        /*//from  ww  w. j  a va2  s.  com
         * Attachments may have been removed in the edit mode. We must
         * refresh the session-bound post before updating attachments.
         */
        final PortletPreferencesWrapper pref = new PortletPreferencesWrapper(request);
        final Post originalPost = getRepositoryDao().getPost(pref.getPortletRepositoryRoot());

        if (originalPost != null) {
            post.getAttachments().clear();
            post.getAttachments().addAll(originalPost.getAttachments());
        }

        final MultipartActionRequest multipartRequest = (MultipartActionRequest) request;

        for (int index = 0; index < multipartRequest.getFileMap().size(); index++) {
            final MultipartFile file = multipartRequest.getFile("attachment" + index);

            if (!file.isEmpty()) {

                logDebug("Uploading attachment file: " + file.getOriginalFilename());
                logDebug("Attachment file size: " + file.getSize());

                final Calendar cldr = Calendar.getInstance(request.getLocale());
                cldr.setTime(new Date());
                final Attachment attachment = Attachment.fromFile(file.getOriginalFilename(),
                        file.getContentType(), cldr, file.getBytes());

                final String title = multipartRequest.getParameter("attachmentTitle" + index);
                attachment.setTitle(title);
                post.getAttachments().add(attachment);
            }

        }
    }
}