Example usage for org.springframework.http HttpHeaders CONTENT_DISPOSITION

List of usage examples for org.springframework.http HttpHeaders CONTENT_DISPOSITION

Introduction

In this page you can find the example usage for org.springframework.http HttpHeaders CONTENT_DISPOSITION.

Prototype

String CONTENT_DISPOSITION

To view the source code for org.springframework.http HttpHeaders CONTENT_DISPOSITION.

Click Source Link

Document

The HTTP Content-Disposition header field name.

Usage

From source file:org.fon.documentmanagementsystem.controllers.DocumentController.java

@RequestMapping(path = "/download/{id}", method = RequestMethod.GET)
public ResponseEntity<byte[]> downloadFile(@PathVariable("id") long id) {
    try {/*from   w  w w  . j  a v  a  2s.c o m*/

        Dokument document = dokumentService.findOne(id);

        HttpHeaders header = new HttpHeaders();
        //header.setContentType(MediaType.valueOf(document.getFajlTip()));

        String nazivfajla = document.getFajl();
        int li = nazivfajla.lastIndexOf('\\');
        String subsnaziv = nazivfajla.substring(li + 1, nazivfajla.length());
        header.set(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + subsnaziv);
        File file = new File(nazivfajla);

        Path path = file.toPath();

        byte[] outputByte = Files.readAllBytes(path);

        String fajltype = Files.probeContentType(path);
        System.out.println(fajltype + " je tip");

        header.setContentType(MediaType.valueOf(fajltype));

        header.setContentLength(outputByte.length);

        return new ResponseEntity<>(outputByte, header, HttpStatus.OK);
    } catch (Exception e) {
        return null;
    }
}

From source file:com.github.zhanhb.ckfinder.download.PathPartial.java

/**
 * Serve the specified resource, optionally including the data content.
 *
 * @param request The servlet request we are processing
 * @param response The servlet response we are creating
 * @param content Should the content be included?
 * @param path the resource to serve//from   w  w w.j  a  v  a2s  .  c  o m
 *
 * @exception IOException if an input/output error occurs
 */
private void serveResource(HttpServletRequest request, HttpServletResponse response, boolean content, Path path)
        throws IOException, ServletException {
    ActionContext context = new ActionContext().put(HttpServletRequest.class, request)
            .put(HttpServletResponse.class, response).put(ServletContext.class, request.getServletContext())
            .put(Path.class, path);
    if (path == null) {
        notFound.handle(context);
        return;
    }
    BasicFileAttributes attr;
    try {
        attr = Files.readAttributes(path, BasicFileAttributes.class);
    } catch (IOException ex) {
        notFound.handle(context);
        return;
    }
    context.put(BasicFileAttributes.class, attr);

    boolean isError = response.getStatus() >= HttpServletResponse.SC_BAD_REQUEST;
    // Check if the conditions specified in the optional If headers are
    // satisfied.
    // Checking If headers
    boolean included = (request.getAttribute(RequestDispatcher.INCLUDE_CONTEXT_PATH) != null);
    String etag = this.eTag.getValue(context);
    if (!included && !isError && !checkIfHeaders(request, response, attr, etag)) {
        return;
    }
    // Find content type.
    String contentType = contentTypeResolver.getValue(context);
    // Get content length
    long contentLength = attr.size();
    // Special case for zero length files, which would cause a
    // (silent) ISE
    boolean serveContent = content && contentLength != 0;
    Range[] ranges = null;
    if (!isError) {
        if (useAcceptRanges) {
            // Accept ranges header
            response.setHeader(HttpHeaders.ACCEPT_RANGES, "bytes");
        }
        // Parse range specifier
        ranges = serveContent ? parseRange(request, response, attr, etag) : FULL;
        // ETag header
        response.setHeader(HttpHeaders.ETAG, etag);
        // Last-Modified header
        response.setDateHeader(HttpHeaders.LAST_MODIFIED, attr.lastModifiedTime().toMillis());
    }
    ServletOutputStream ostream = null;
    if (serveContent) {
        ostream = response.getOutputStream();
    }

    String disposition = contentDisposition.getValue(context);
    if (disposition != null) {
        response.setHeader(HttpHeaders.CONTENT_DISPOSITION, disposition);
    }

    // Check to see if a Filter, Valve of wrapper has written some content.
    // If it has, disable range requests and setting of a content length
    // since neither can be done reliably.
    if (isError || ranges == FULL) {
        // Set the appropriate output headers
        if (contentType != null) {
            log.debug("serveFile: contentType='{}'", contentType);
            response.setContentType(contentType);
        }
        if (contentLength >= 0) {
            setContentLengthLong(response, contentLength);
        }
        // Copy the input stream to our output stream (if requested)
        if (serveContent) {
            log.trace("Serving bytes");
            Files.copy(path, ostream);
        }
    } else if (ranges != null && ranges.length != 0) {
        // Partial content response.
        response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
        if (ranges.length == 1) {
            Range range = ranges[0];
            response.addHeader(HttpHeaders.CONTENT_RANGE, range.toString());
            long length = range.end - range.start + 1;
            setContentLengthLong(response, length);
            if (contentType != null) {
                log.debug("serveFile: contentType='{}'", contentType);
                response.setContentType(contentType);
            }
            if (serveContent) {
                try (InputStream stream = Files.newInputStream(path)) {
                    copyRange(stream, ostream, range, new byte[Math.min((int) length, 8192)]);
                }
            }
        } else {
            response.setContentType("multipart/byteranges; boundary=" + MIME_SEPARATION);
            if (serveContent) {
                copy(path, ostream, ranges, contentType, new byte[Math.min((int) contentLength, 8192)]);
            }
        }
    }
}

From source file:org.openlmis.fulfillment.web.OrderController.java

/**
 * Exporting order to csv.//  ww w  . ja  v  a 2  s.  c o  m
 *
 * @param orderId  UUID of order to print
 * @param type     export type
 * @param response HttpServletResponse object
 */
@RequestMapping(value = "/orders/{id}/export", method = RequestMethod.GET)
@ResponseStatus(HttpStatus.OK)
public void export(@PathVariable("id") UUID orderId,
        @RequestParam(value = "type", required = false, defaultValue = "csv") String type,
        HttpServletResponse response) throws IOException {
    if (!"csv".equals(type)) {
        String msg = "Export type: " + type + " not allowed";
        LOGGER.warn(msg);
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, msg);
        return;
    }

    Order order = orderRepository.findOne(orderId);

    if (order == null) {
        String msg = "Order does not exist.";
        LOGGER.warn(msg);
        response.sendError(HttpServletResponse.SC_NOT_FOUND, msg);
        return;
    }

    permissionService.canViewOrder(order);

    OrderFileTemplate orderFileTemplate = orderFileTemplateService.getOrderFileTemplate();

    if (orderFileTemplate == null) {
        String msg = "Could not export Order, because Order Template File not found";
        LOGGER.warn(msg);
        response.sendError(HttpServletResponse.SC_NOT_FOUND, msg);
        return;
    }

    response.setContentType("text/csv");
    response.addHeader(HttpHeaders.CONTENT_DISPOSITION,
            DISPOSITION_BASE + orderFileTemplate.getFilePrefix() + order.getOrderCode() + ".csv");

    try {
        csvHelper.writeCsvFile(order, orderFileTemplate, response.getWriter());
    } catch (IOException ex) {
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                "Error occurred while exporting order to csv.");
        LOGGER.error("Error occurred while exporting order to csv", ex);
    }
}

From source file:de.metas.ui.web.window.controller.WindowRestController.java

@RequestMapping(value = "/{windowId}/{documentId}/print/{filename:.*}", method = RequestMethod.GET)
public ResponseEntity<byte[]> getDocumentPrint(@PathVariable("windowId") final int adWindowId //
        , @PathVariable("documentId") final String documentId //
        , @PathVariable("filename") final String filename) {
    userSession.assertLoggedIn();//from  ww  w. j  av  a  2s  . co m

    final DocumentPath documentPath = DocumentPath.rootDocumentPath(DocumentType.Window, adWindowId,
            documentId);

    final Document document = documentCollection.getDocument(documentPath);
    final DocumentEntityDescriptor entityDescriptor = document.getEntityDescriptor();

    final ProcessExecutionResult processExecutionResult = ProcessInfo.builder().setCtx(userSession.getCtx())
            .setAD_Process_ID(entityDescriptor.getPrintProcessId())
            .setRecord(entityDescriptor.getTableName(), document.getDocumentIdAsInt()).setPrintPreview(true)
            .setJRDesiredOutputType(OutputType.PDF)
            //
            .buildAndPrepareExecution().onErrorThrowException().switchContextWhenRunning().executeSync()
            .getResult();

    final byte[] reportData = processExecutionResult.getReportData();
    final String reportContentType = processExecutionResult.getReportContentType();

    final HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.parseMediaType(reportContentType));
    headers.set(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=\"" + filename + "\"");
    headers.setCacheControl("must-revalidate, post-check=0, pre-check=0");
    final ResponseEntity<byte[]> response = new ResponseEntity<>(reportData, headers, HttpStatus.OK);
    return response;
}

From source file:de.metas.ui.web.window.controller.WindowRestController.java

@GetMapping("/{windowId}/{documentId}/attachments/{id}")
public ResponseEntity<byte[]> getAttachmentById(@PathVariable("windowId") final int adWindowId //
        , @PathVariable("documentId") final String documentId //
        , @PathVariable("id") final int id) {
    userSession.assertLoggedIn();/*  w  w  w  . j av a2 s .c o m*/

    final DocumentPath documentPath = DocumentPath.rootDocumentPath(DocumentType.Window, adWindowId,
            documentId);
    final Document document = documentCollection.getDocument(documentPath);

    final MAttachmentEntry entry = Services.get(IAttachmentBL.class).getEntryForModelById(document, id);
    if (entry == null) {
        throw new EntityNotFoundException("No attachment found (ID=" + id + ")");
    }

    final String entryFilename = entry.getFilename();
    final byte[] entryData = entry.getData();
    if (entryData == null || entryData.length == 0) {
        throw new EntityNotFoundException("No attachment found (ID=" + id + ")");
    }

    final String entryContentType = entry.getContentType();

    final HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.parseMediaType(entryContentType));
    headers.set(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=\"" + entryFilename + "\"");
    headers.setCacheControl("must-revalidate, post-check=0, pre-check=0");
    final ResponseEntity<byte[]> response = new ResponseEntity<>(entryData, headers, HttpStatus.OK);
    return response;
}

From source file:access.controller.AccessController.java

/**
 * @param type//ww  w.j  a va2s .  co  m
 *            MediaType to set http header content type
 * @param fileName
 *            file name to set for content disposition
 * @param bytes
 *            file bytes
 * @return ResponseEntity
 */
private ResponseEntity<byte[]> getResponse(MediaType type, String fileName, byte[] bytes) {
    HttpHeaders header = new HttpHeaders();
    header.setContentType(type);
    header.set(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + fileName);
    header.setContentLength(bytes.length);
    return new ResponseEntity<>(bytes, header, HttpStatus.OK);
}

From source file:com.siblinks.ws.service.impl.UploadEssayServiceImpl.java

/**
 * {@inheritDoc}/*from   w w  w  . j ava  2 s . co m*/
 */
@Override
@RequestMapping(value = "/download", method = RequestMethod.GET)
public void download(@RequestParam("essayId") final String essayId, final String type,
        final HttpServletRequest request, final HttpServletResponse response) {

    // get output stream of the response
    OutputStream outStream = null;
    InputStream inputStream = null;
    try {
        String entityName = "";
        if (type.equals("S")) {
            entityName = SibConstants.SqlMapper.SQL_STUDENT_DOWNLOAD;
        } else if (type.equals("M")) {
            entityName = SibConstants.SqlMapper.SQL_MENTOR_DOWNLOAD;
        }
        Object[] queryParams = { essayId };

        Download file = dao.download(entityName, queryParams);

        // get MIME type of the file
        String mimeType = file.getMimeType();
        String fileName = file.getFileName();
        if (mimeType == null) {
            // set to binary type if MIME mapping not found
            mimeType = "application/octet-stream";
        }
        // set content attributes for the response
        response.setContentType(mimeType);
        response.setContentLength(Integer.parseInt(file.getFilesize()));
        response.setCharacterEncoding("utf-8");

        response.setHeader(HttpHeaders.CONTENT_DISPOSITION,
                "attachment; filename=" + getFilenameUnicode(fileName));

        outStream = response.getOutputStream();

        byte[] buffer = new byte[BUFFER_SIZE];
        int bytesRead = -1;
        inputStream = file.getInputStream();
        // write bytes read from the input stream into the output stream
        while ((bytesRead = inputStream.read(buffer)) != -1) {
            outStream.write(buffer, 0, bytesRead);
        }

    } catch (Exception e) {
        e.printStackTrace();
        logger.error(e, e.getCause());
    } finally {
        try {
            if (inputStream != null) {
                inputStream.close();
            }
            if (outStream != null) {
                outStream.close();
            }
        } catch (IOException e) {
            // Do nothing
        }
    }

}

From source file:de.metas.ui.web.letter.LetterRestController.java

private ResponseEntity<byte[]> createPDFResponseEntry(final byte[] pdfData) {
    final String pdfFilename = Services.get(IMsgBL.class).getMsg(Env.getCtx(), Letters.MSG_Letter);
    final HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_PDF);
    headers.set(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=\"" + pdfFilename + "\"");
    headers.setCacheControl("must-revalidate, post-check=0, pre-check=0");
    final ResponseEntity<byte[]> response = new ResponseEntity<>(pdfData, headers, HttpStatus.OK);
    return response;
}

From source file:eu.europa.ec.grow.espd.controller.EspdController.java

private void downloadEspdFile(@PathVariable String agent, @ModelAttribute("espd") EspdDocument espd,
        HttpServletResponse response) throws IOException {
    try (CountingOutputStream out = new CountingOutputStream(response.getOutputStream())) {
        response.setContentType(APPLICATION_XML_VALUE);
        if ("eo".equals(agent)) {
            response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"espd-response.xml\"");
            exchangeMarshaller.generateEspdResponse(espd, out);
        } else {/*from  ww w. j  a  v  a  2 s. c  om*/
            response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"espd-request.xml\"");
            exchangeMarshaller.generateEspdRequest(espd, out);
        }
        response.setHeader(HttpHeaders.CONTENT_LENGTH, String.valueOf(out.getByteCount()));
        out.flush();
    }
}

From source file:net.turnbig.pandora.web.Servlets.java

/**
 * ??Header./*w w w.j av  a2  s .co  m*/
 * 
 * @param fileName ???.
 */
public static void setFileDownloadHeader(HttpServletRequest request, HttpServletResponse response,
        String fileName) {
    try {
        String agent = request.getHeader("User-Agent");
        boolean isMSIE = ((agent != null) && (agent.indexOf("MSIE") != -1));
        String encoded = isMSIE ? URLEncoder.encode(fileName, "UTF-8")
                : new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
        response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + encoded + "\"");
    } catch (UnsupportedEncodingException e) {

    }
}