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:com.example.multipart.MultipartServiceImpl.java

@Override
public void downloadByteArrayData(byte[] content, String contentType, String filename,
        HttpServletResponse response) throws IOException {

    InputStream is = new ByteArrayInputStream(content);

    response.setContentType(contentType);
    response.addHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=\"" + filename + "\"");
    copy(is, response.getOutputStream());
    response.flushBuffer();//from  ww w. ja v a  2  s  .  c  o  m
}

From source file:pw.spn.mptg.controller.ProjectTemplateController.java

@PostMapping(produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
public ResponseEntity<byte[]> generate(@ModelAttribute PomTemplate pomTemplate) {
    HttpHeaders headers = new HttpHeaders();
    headers.add(HttpHeaders.CONTENT_DISPOSITION,
            String.format(CONTENT_DISPOSITION_VALUE, pomTemplate.getArtifactId()));
    ResponseEntity<byte[]> responseEntity = new ResponseEntity<byte[]>(
            projectService.generateProjectAndZip(pomTemplate), headers, HttpStatus.OK);
    return responseEntity;
}

From source file:eu.freme.eservices.publishing.ServiceRestController.java

@RequestMapping(value = "/e-publishing/html", method = RequestMethod.POST)
public ResponseEntity<byte[]> htmlToEPub(@RequestParam("htmlZip") MultipartFile file,
        @RequestParam("metadata") String jMetadata)
        throws IOException, InvalidZipException, EPubCreationException, MissingMetadataException {
    Gson gson = new Gson();
    Metadata metadata = gson.fromJson(jMetadata, Metadata.class);
    MultiValueMap<String, String> headers = new HttpHeaders();
    headers.add(HttpHeaders.CONTENT_TYPE, "Application/epub+zip");
    String filename = file.getName();
    headers.add(HttpHeaders.CONTENT_DISPOSITION, "Attachment; filename=" + filename.split("\\.")[0] + ".epub");
    try (InputStream in = file.getInputStream()) {
        return new ResponseEntity<>(epubAPI.createEPUB(metadata, in), headers, HttpStatus.OK);
    }/*from w  ww  .j ava  2 s.co m*/
}

From source file:app.controller.ResourceController.java

@GetMapping(value = "/download/{resourceType:.*}")
public void download(HttpServletRequest request, HttpServletResponse response, @RequestParam String filename,
        @PathVariable int resourceType) throws IOException {
    logger.info("---------------download resource-----------------");
    FileResource resource = new FileResource();
    int result = resourceService.download(filename, resourceType, resource);
    if (result != BaseResponse.COMMON_SUCCESS) {
        throw new ResourceNotFoundException();
    }//from  w ww  . j  a v  a  2  s .c o m
    File file = resource.file;

    // get MIME type of the file
    ServletContext context = request.getServletContext();
    String mimeType = context.getMimeType(filename);
    if (mimeType == null) {
        mimeType = MediaType.APPLICATION_OCTET_STREAM_VALUE;
    }

    response.setContentType(mimeType);
    response.setContentLength((int) file.length());
    response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + filename);

    BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
    FileCopyUtils.copy(new BufferedInputStream(new FileInputStream(file)), out);
}

From source file:com.intuit.karate.demo.controller.UploadController.java

@GetMapping("/{id:.+}")
public ResponseEntity<Resource> download(@PathVariable String id) throws Exception {
    String filePath = FILES_BASE + id;
    File file = new File(filePath);
    File meta = new File(filePath + "_meta.txt");
    String name = FileUtils.readFileToString(meta, "utf-8");
    return ResponseEntity.ok().header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + name + "\"")
            .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_OCTET_STREAM_VALUE)
            .body(new FileSystemResource(file));
}

From source file:bibibi.controllers.CitationsController.java

@RequestMapping(value = "/export", method = RequestMethod.GET)
public HttpEntity<FileSystemResource> getFile() throws IOException {
    BibWriter bw = new BibWriter("export", this.citationRepository.findAll());
    bw.writeFile();/*from w ww .jav  a2  s  .c o  m*/

    HttpHeaders header = new HttpHeaders();
    header.setContentType(MediaType.APPLICATION_OCTET_STREAM);
    header.set(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + bw.getFile().getName());
    header.setContentLength(bw.getFile().length());

    return new HttpEntity<>(new FileSystemResource(bw.getFile()), header);
}

From source file:de.metas.ui.web.upload.ImageRestController.java

@GetMapping("/{imageId}")
@ResponseBody/*w w w . ja v a2 s .  c  om*/
public ResponseEntity<byte[]> getImage(@PathVariable final int imageId) {
    userSession.assertLoggedIn();

    if (imageId <= 0) {
        throw new IllegalArgumentException("Invalid image id");
    }

    final MImage adImage = MImage.get(userSession.getCtx(), imageId);
    if (adImage == null || adImage.getAD_Image_ID() <= 0) {
        throw new EntityNotFoundException("Image id not found: " + imageId);
    }

    final boolean hasAccess = userSession.getUserRolePermissions().canView(adImage.getAD_Client_ID(),
            adImage.getAD_Org_ID(), I_AD_Image.Table_ID, adImage.getAD_Image_ID());
    if (!hasAccess) {
        throw new EntityNotFoundException("Image id not found: " + imageId);
    }

    final String imageName = adImage.getName();
    final byte[] imageData = adImage.getData();
    final String contentType = MimeType.getMimeType(imageName);

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

From source file:org.ow2.proactive.workflow_catalog.rest.controller.WorkflowControllerTest.java

@Test
public void testGetWorkflowsAsArchive() throws IOException {
    HttpServletResponse response = mock(HttpServletResponse.class);
    ServletOutputStream sos = mock(ServletOutputStream.class);
    when(response.getOutputStream()).thenReturn(sos);
    List<Long> idList = new ArrayList<>();
    idList.add(0L);//from   w ww . j  a  v a2s .co  m
    workflowController.get(1L, idList, Optional.of("zip"), response);
    verify(workflowService, times(1)).getWorkflowsAsArchive(1L, idList);
    verify(response, times(1)).setStatus(HttpServletResponse.SC_OK);
    verify(response, times(1)).setContentType("application/zip");
    verify(response, times(1)).addHeader(HttpHeaders.CONTENT_ENCODING, "binary");
    verify(response, times(1)).addHeader(HttpHeaders.CONTENT_DISPOSITION,
            "attachment; filename=\"archive.zip\"");
    verify(sos, times(1)).write(Mockito.any());
    verify(sos, times(1)).flush();
}

From source file:org.ow2.proactive.workflow_catalog.rest.controller.WorkflowController.java

@ApiOperation(value = "Gets a workflow's metadata by IDs", notes = "Returns metadata associated to the latest revision of the workflow.")
@ApiResponses(value = @ApiResponse(code = 404, message = "Bucket or workflow not found"))
@RequestMapping(value = "/buckets/{bucketId}/workflows/{idList}", method = GET)
public ResponseEntity<?> get(@PathVariable Long bucketId, @PathVariable List<Long> idList,
        @ApiParam(value = "Force response to return workflow XML content when set to 'xml'. Or extract workflows as ZIP when set to 'zip'.") @RequestParam(required = false) Optional<String> alt,
        HttpServletResponse response) throws MalformedURLException {
    if (alt.isPresent() && ZIP_EXTENSION.equals(alt.get())) {
        byte[] zip = workflowService.getWorkflowsAsArchive(bucketId, idList);

        response.setStatus(HttpServletResponse.SC_OK);
        response.setContentType("application/zip");
        response.addHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"archive.zip\"");
        response.addHeader(HttpHeaders.CONTENT_ENCODING, "binary");
        try {//from w w w  .  ja  va2  s  . c om
            response.getOutputStream().write(zip);
            response.getOutputStream().flush();
        } catch (IOException ioe) {
            throw new RuntimeException(ioe);
        }
        return ResponseEntity.ok().build();
    } else {
        if (idList.size() == 1) {
            return workflowService.getWorkflowMetadata(bucketId, idList.get(0), alt);
        } else {
            return ResponseEntity.badRequest().build();
        }
    }
}

From source file:de.metas.ui.web.process.ProcessRestController.java

@RequestMapping(value = "/{processId}/{pinstanceId}/print/{filename:.*}", method = RequestMethod.GET)
public ResponseEntity<byte[]> getReport(@PathVariable("processId") final int processId_NOTUSED //
        , @PathVariable("pinstanceId") final int pinstanceId //
        , @PathVariable("filename") final String filename //
) {/*from www . java  2 s  . c o  m*/
    final ProcessInstanceResult executionResult = instancesRepository.forProcessInstanceReadonly(pinstanceId,
            processInstance -> processInstance.getExecutionResult());

    final String reportFilename = executionResult.getReportFilename();
    final String reportContentType = executionResult.getReportContentType();
    final byte[] reportData = executionResult.getReportData();

    final String reportFilenameEffective = Util.coalesce(filename, reportFilename, "");

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