Example usage for org.springframework.http HttpHeaders setContentDispositionFormData

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

Introduction

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

Prototype

public void setContentDispositionFormData(String name, @Nullable String filename) 

Source Link

Document

Set the Content-Disposition header when creating a "multipart/form-data" request.

Usage

From source file:com.yyl.common.utils.excel.ExcelTools.java

public static ResponseEntity<byte[]> export(ByteArrayOutputStream bOutputStream, String fileName) {
    try {//from  w  w  w.j av a2 s  . c om
        fileName = new String((fileName + DateUtils.formatDate(new Date(), "yyyy-MM-dd") + ".xls").getBytes(),
                "iso-8859-1");
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }

    HttpHeaders headers = new HttpHeaders();
    headers.setContentDispositionFormData("attachment", fileName);
    headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);

    return new ResponseEntity<byte[]>(bOutputStream.toByteArray(), headers, HttpStatus.CREATED);
}

From source file:org.ng200.openolympus.controller.solution.SolutionDownloadController.java

@PreAuthorize(SecurityExpressionConstants.IS_ADMIN + SecurityExpressionConstants.OR + '('
        + SecurityExpressionConstants.IS_USER + SecurityExpressionConstants.AND
        + SecurityExpressionConstants.USER_IS_OWNER + SecurityExpressionConstants.AND
        + "@oolsec.isSolutionInCurrentContest(#solution)" + ')')
@RequestMapping(method = RequestMethod.GET)
public @ResponseBody ResponseEntity<FileSystemResource> solutionDownload(final HttpServletRequest request,
        final Model model, @RequestParam(value = "id") final Solution solution, final Principal principal) {
    if (principal == null || (!solution.getUser().getUsername().equals(principal.getName())
            && !request.isUserInRole(Role.SUPERUSER))) {
        throw new InsufficientAuthenticationException(
                "You attempted to download a solution that doesn't belong to you!");
    }//w  ww .  ja v a2s .  co m
    Assertions.resourceExists(solution);

    final HttpHeaders headers = new HttpHeaders();
    headers.setContentDispositionFormData("attachment",
            this.storageService.getSolutionFile(solution).getFileName().toString());
    return new ResponseEntity<FileSystemResource>(
            new FileSystemResource(this.storageService.getSolutionFile(solution).toFile()), headers,
            HttpStatus.OK);
}

From source file:com.castlemock.web.basis.web.mvc.controller.project.ExportProjectController.java

/**
 * Creates and return a view that provides the required functionality
 * to export a project./*from  w ww  .  ja  va2s.c o m*/
 * @param projectType The type of the project that should be exported
 * @param projectId The id of the project that should be exported
 * @return A view that provides the required functionality to export a project
 */
@PreAuthorize("hasAuthority('READER') or hasAuthority('MODIFIER') or hasAuthority('ADMIN')")
@RequestMapping(value = "{projectType}/project/{projectId}/export", method = RequestMethod.GET)
public ResponseEntity<String> defaultPage(@PathVariable final String projectType,
        @PathVariable final String projectId) {
    final String exportedProject = projectServiceFacade.exportProject(projectType, projectId);

    HttpHeaders respHeaders = new HttpHeaders();
    respHeaders.setContentType(MediaType.TEXT_XML);
    respHeaders.setContentDispositionFormData("attachment",
            "project-" + projectType + "-" + projectId + ".xml");

    return new ResponseEntity<String>(exportedProject, respHeaders, HttpStatus.OK);
}

From source file:io.github.autsia.crowly.controllers.DashboardController.java

@RequestMapping(value = "/campaigns/export/{campaignId}", method = RequestMethod.GET)
public ResponseEntity<byte[]> export(@PathVariable("campaignId") String campaignId, ModelMap model)
        throws DocumentException {
    Document document = new Document();
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    PdfWriter.getInstance(document, byteArrayOutputStream);
    document.open();//from  w w w  .  j a  v  a 2s. c  om
    Gson gson = new Gson();
    String json = gson.toJson(mentionRepository.findByCampaignId(campaignId));
    document.add(new Paragraph(json));
    document.close();

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.parseMediaType("application/pdf"));
    String filename = "output.pdf";
    headers.setContentDispositionFormData(filename, filename);
    headers.setCacheControl("must-revalidate, post-check=0, pre-check=0");
    ResponseEntity<byte[]> response = new ResponseEntity<byte[]>(byteArrayOutputStream.toByteArray(), headers,
            HttpStatus.OK);
    return response;
}

From source file:com.orange.clara.cloud.poc.s3.controller.PocS3Controller.java

@RequestMapping(value = "/download/{fileName:.*}", method = RequestMethod.GET)
public ResponseEntity<InputStreamResource> download(@PathVariable String fileName) throws IOException {
    Blob blob = this.blobStore.getBlob(fileName);

    HttpHeaders respHeaders = new HttpHeaders();

    respHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);
    respHeaders.setContentLength(blob.getPayload().getContentMetadata().getContentLength());
    respHeaders.setContentDispositionFormData("attachment", fileName);

    InputStream inputStream = blob.getPayload().openStream();

    InputStreamResource isr = new InputStreamResource(inputStream);
    return new ResponseEntity<>(isr, respHeaders, HttpStatus.OK);
}

From source file:cn.mypandora.controller.BaseUserController.java

/**
 * //w  ww  .ja v a 2 s . c  om
 */
@ApiOperation(value = "")
@RequestMapping(value = "/down/{currentPage}", method = RequestMethod.GET)
public ResponseEntity<byte[]> down(@PathVariable int currentPage, HttpServletRequest request)
        throws IOException {
    // ???Excel?
    PageInfo<BaseUser> page = new PageInfo<>();
    page.setPageNum(currentPage);
    page = baseUserService.findPageUserByCondition("pageUsers", null, page);
    // ???
    String rootpath = request.getSession().getServletContext().getRealPath("/");
    String fileName = MyDateUtils.getCurrentDate() + XLSX;
    MyExcelUtil.writeExcel(rootpath + "download" + fileName, "sheet1", "ID,??,,,",
            page.getList(), BaseUser.class, "id,username,sex,birthday,credits");
    // 
    File file = new File(rootpath + "download" + fileName);
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
    headers.setContentDispositionFormData("attachment", fileName);
    return new ResponseEntity<>(FileUtils.readFileToByteArray(file), headers, HttpStatus.CREATED);
}

From source file:com.fengduo.bee.web.controller.product.ProductController.java

/**
 * pdf?//ww  w.j a  v a 2s .c  om
 * 
 * @param id
 * @return
 * @throws IOException
 */
@RequestMapping("/item/{id}/download")
public ResponseEntity<byte[]> download(@PathVariable("id") Long id) throws IOException {
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
    headers.setContentDispositionFormData("attachment", ".pdf");
    String name = "";
    name = new String(name.getBytes(), "ISO8859-1");
    headers.set("content-disposition", "attachment;filename=" + name + ".pdf");

    if (Argument.isNotPositive(id)) {
        return new ResponseEntity<byte[]>(null, headers, HttpStatus.CREATED);
    }
    ItemFinance itemFinance = itemService.getItemFinanceByItemId(id);
    if (itemFinance == null) {
        return new ResponseEntity<byte[]>(null, headers, HttpStatus.CREATED);
    }
    String url = itemFinance.getPdfUrl();
    File file = fileService.getFile(url);
    if (file == null) {
        return new ResponseEntity<byte[]>(null, headers, HttpStatus.CREATED);
    }

    return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), headers, HttpStatus.CREATED);
}

From source file:ca.intelliware.ihtsdo.mlds.web.rest.MemberResource.java

private ResponseEntity<?> downloadFile(HttpServletRequest request, File file) throws SQLException, IOException {
    if (file == null) {
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    } else if (file.getLastUpdated() != null) {
        long ifModifiedSince = request.getDateHeader("If-Modified-Since");
        long lastUpdatedSecondsFloor = file.getLastUpdated().getMillis() / 1000 * 1000;
        if (ifModifiedSince != -1 && lastUpdatedSecondsFloor <= ifModifiedSince) {
            return new ResponseEntity<>(HttpStatus.NOT_MODIFIED);
        }//ww w  .  j a  v  a  2 s  . c o m
    }

    HttpHeaders httpHeaders = new HttpHeaders();
    httpHeaders.setContentType(MediaType.valueOf(file.getMimetype()));
    httpHeaders.setContentLength(file.getContent().length());
    httpHeaders.setContentDispositionFormData("file", file.getFilename());
    if (file.getLastUpdated() != null) {
        httpHeaders.setLastModified(file.getLastUpdated().getMillis());
    }

    byte[] byteArray = IOUtils.toByteArray(file.getContent().getBinaryStream());
    org.springframework.core.io.Resource contents = new ByteArrayResource(byteArray);
    return new ResponseEntity<org.springframework.core.io.Resource>(contents, httpHeaders, HttpStatus.OK);
}

From source file:org.zlogic.vogon.web.controller.DataController.java

/**
 * Returns all data/*from   w  w w. j  a  va  2  s . com*/
 *
 * @param userPrincipal the authenticated user
 * @return the HTTPEntity for the file download
 */
@RequestMapping(value = "/export/xml", method = { RequestMethod.GET, RequestMethod.POST })
public HttpEntity<byte[]> exportDataXML(@AuthenticationPrincipal VogonSecurityUser userPrincipal)
        throws RuntimeException {
    VogonUser user = userRepository.findByUsernameIgnoreCase(userPrincipal.getUsername());
    try {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        XmlExporter exporter = new XmlExporter(outStream);
        Sort accountSort = new Sort(new Sort.Order(Sort.Direction.ASC, "id"));//NOI18N
        Sort transactionSort = new Sort(new Sort.Order(Sort.Direction.ASC, "id"));//NOI18N
        exporter.exportData(user, accountRepository.findByOwner(user, accountSort),
                transactionRepository.findByOwner(user, transactionSort), null);

        String date = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss").format(new Date()); //NOI18N

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_XML);
        headers.setContentLength(outStream.size());
        headers.setContentDispositionFormData("attachment", "vogon-" + date + ".xml"); //NOI18N //NOI18N

        return new HttpEntity<>(outStream.toByteArray(), headers);
    } catch (VogonExportException ex) {
        throw new RuntimeException(ex);
    }
}

From source file:org.zlogic.vogon.web.controller.DataController.java

/**
 * Returns all data/*from  w  w  w .  j a  va  2 s  .  c o  m*/
 *
 * @param userPrincipal the authenticated user
 * @return the HTTPEntity for the file download
 */
@RequestMapping(value = "/export/json", method = { RequestMethod.GET, RequestMethod.POST })
public HttpEntity<byte[]> exportDataJSON(@AuthenticationPrincipal VogonSecurityUser userPrincipal)
        throws RuntimeException {
    VogonUser user = userRepository.findByUsernameIgnoreCase(userPrincipal.getUsername());
    try {
        ClassExporter exporter = new ClassExporter();
        Sort accountSort = new Sort(new Sort.Order(Sort.Direction.ASC, "id"));//NOI18N
        Sort transactionSort = new Sort(new Sort.Order(Sort.Direction.ASC, "id"));//NOI18N

        exporter.exportData(user, accountRepository.findByOwner(user, accountSort),
                transactionRepository.findByOwner(user, transactionSort), null);
        ExportedData exportedData = exporter.getExportedData();

        //Process transactions for JSON
        List<FinanceTransactionJson> processedTransactions = initializationHelper
                .initializeTransactions(exportedData.getTransactions());
        exportedData.getTransactions().clear();
        for (FinanceTransactionJson transaction : processedTransactions)
            exportedData.getTransactions().add(transaction);

        //Convert to JSON
        byte[] output = jsonMapper.writer().withDefaultPrettyPrinter().writeValueAsString(exportedData)
                .getBytes("utf-8"); //NOI18N

        String date = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss").format(new Date()); //NOI18N

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        headers.setContentLength(output.length);
        headers.setContentDispositionFormData("attachment", "vogon-" + date + ".json"); //NOI18N //NOI18N

        return new HttpEntity<>(output, headers);
    } catch (VogonExportException | IOException ex) {
        throw new RuntimeException(ex);
    }
}