List of usage examples for javax.servlet.http HttpServletResponse setContentLength
public void setContentLength(int len);
From source file:org.shareok.data.webserv.WebUtil.java
public static void downloadFileFromServer(HttpServletResponse response, String downloadPath) { try {/*from w w w .j a v a 2 s . co m*/ File file = new File(downloadPath); if (!file.exists()) { String errorMessage = "Sorry. The file you are looking for does not exist"; System.out.println(errorMessage); OutputStream outputStream = response.getOutputStream(); outputStream.write(errorMessage.getBytes(Charset.forName("UTF-8"))); outputStream.close(); return; } String mimeType = URLConnection.guessContentTypeFromName(file.getName()); if (mimeType == null) { System.out.println("mimetype is not detectable, will take default"); mimeType = "application/octet-stream"; } response.setContentType(mimeType); /* "Content-Disposition : inline" will show viewable types [like images/text/pdf/anything viewable by browser] right on browser while others(zip e.g) will be directly downloaded [may provide save as popup, based on your browser setting.]*/ response.setHeader("Content-Disposition", String.format("attachment; filename=\"" + file.getName() + "\"")); /* "Content-Disposition : attachment" will be directly download, may provide save as popup, based on your browser setting*/ //response.setHeader("Content-Disposition", String.format("attachment; filename=\"%s\"", file.getName())); response.setContentLength((int) file.length()); InputStream inputStream = new BufferedInputStream(new FileInputStream(file)); //Copy bytes from source to destination(outputstream in this example), closes both streams. FileCopyUtils.copy(inputStream, response.getOutputStream()); } catch (IOException ioex) { logger.error("Cannot download file responding to downloading resquest!", ioex); } }
From source file:info.magnolia.rendering.engine.RenderingFilter.java
private InputStream getNodedataAsStream(String path, Session session, HttpServletResponse res) { log.debug("getNodedataAstream for path \"{}\"", path); try {/*from ww w . java2s. c o m*/ Node atom = session.getNode(path); if (atom != null) { if (atom.hasProperty(JcrConstants.JCR_DATA)) { Property sizeProperty = atom.getProperty("size"); String sizeString = sizeProperty == null ? "" : sizeProperty.getString(); if (NumberUtils.isNumber(sizeString)) { res.setContentLength(Integer.parseInt(sizeString)); } Property streamProperty = atom.getProperty(JcrConstants.JCR_DATA); return streamProperty.getStream(); } } log.warn("Resource not found: [{}]", path); } catch (RepositoryException e) { log.error("RepositoryException while reading Resource [" + path + "]", e); } return null; }
From source file:com.benfante.minimark.controllers.ResultsController.java
@RequestMapping public void pdfs(@RequestParam("id") Long id, HttpServletRequest req, HttpServletResponse res, Locale locale) { Assessment assessment = assessmentDao.get(id); userProfileBo.checkEditAuthorization(assessment); List<AssessmentFilling> assessments = assessmentFillingDao .findByAssessmentIdOrderByLastNameAndFirstNameAndIdentifier(id); OutputStream out = null;/*from www .j a v a 2 s . c o m*/ try { byte[] pdfBytes = assessmentPdfBuilder.buildPdf(assessments, Utilities.getBaseUrl(req), locale); out = res.getOutputStream(); res.setContentType("application/pdf"); res.setContentLength(pdfBytes.length); res.setHeader("Content-Disposition", " attachment; filename=\"" + assessment.getTitle() + ".pdf\""); res.setHeader("Expires", "0"); res.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0"); res.setHeader("Pragma", "public"); out.write(pdfBytes); out.flush(); } catch (Exception ex) { logger.error("Can't build PDF file for " + assessment.getTitle(), ex); } finally { if (out != null) { try { out.close(); } catch (IOException ioe) { } } } }
From source file:edu.csudh.goTorosBank.WithdrawServlet.java
@Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //File blueCheck = new File("blank-blue-check.jpg"); File blueCheck = new File(request.getParameter("filename")); String pathToWeb = getServletContext().getRealPath("/" + blueCheck); ServletContext cntx = request.getServletContext(); String mime = cntx.getMimeType(pathToWeb); response.setContentType(mime);/*w w w .j av a2 s. com*/ try { File file = new File(pathToWeb); response.setContentLength((int) file.length()); FileInputStream in = new FileInputStream(file); OutputStream out = response.getOutputStream(); // Copy the contents of the file to the output stream byte[] buf = new byte[1024]; int count; while ((count = in.read(buf)) >= 0) { out.write(buf, 0, count); } out.close(); in.close(); response.setHeader("Content-Transfer-Encoding", "binary"); response.setHeader("Content-Disposition", "attachment; filename=\"" + blueCheck.getName() + "\"");//fileName; } catch (Exception e) { response.getWriter().write(e.getMessage()); } }
From source file:com.nemesis.admin.UploadServlet.java
/** * @param request//from w w w . j av a 2s . c om * @param response * @throws javax.servlet.ServletException * @throws java.io.IOException * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse * response) * */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if (request.getParameter("getfile") != null && !request.getParameter("getfile").isEmpty()) { File file = getFile(request, request.getParameter("getfile")); if (file.exists()) { int bytes = 0; try (ServletOutputStream op = response.getOutputStream()) { response.setContentType(getMimeType(file)); response.setContentLength((int) file.length()); response.setHeader("Content-Disposition", "inline; filename=\"" + file.getName() + "\""); byte[] bbuf = new byte[1024]; DataInputStream in = new DataInputStream(new FileInputStream(file)); while ((in != null) && ((bytes = in.read(bbuf)) != -1)) { op.write(bbuf, 0, bytes); } in.close(); op.flush(); } } } else if (request.getParameter("delfile") != null && !request.getParameter("delfile").isEmpty()) { File file = getFile(request, request.getParameter("delfile")); if (file.exists()) { file.delete(); // TODO:check and report success } } else if (request.getParameter("getthumb") != null && !request.getParameter("getthumb").isEmpty()) { File file = getFile(request, request.getParameter("getthumb")); if (file.exists()) { System.out.println(file.getAbsolutePath()); String mimetype = getMimeType(file); if (mimetype.endsWith("png") || mimetype.endsWith("jpeg") || mimetype.endsWith("jpg") || mimetype.endsWith("gif")) { BufferedImage im = ImageIO.read(file); if (im != null) { int newWidth = 75; if (request.getParameter("w") != null) { try { newWidth = Integer.parseInt(request.getParameter("w")); } catch (Exception e) { //Se mantiene el valor por defecto de 75 } } BufferedImage thumb = Scalr.resize(im, newWidth); if (request.getParameter("h") != null) { try { thumb = Scalr.crop(thumb, newWidth, Integer.parseInt(request.getParameter("h"))); } catch (IllegalArgumentException | ImagingOpException e) { //Se mantienen las proporciones. } } ByteArrayOutputStream os = new ByteArrayOutputStream(); if (mimetype.endsWith("png")) { ImageIO.write(thumb, "PNG", os); response.setContentType("image/png"); } else if (mimetype.endsWith("jpeg")) { ImageIO.write(thumb, "jpg", os); response.setContentType("image/jpeg"); } else if (mimetype.endsWith("jpg")) { ImageIO.write(thumb, "jpg", os); response.setContentType("image/jpeg"); } else { ImageIO.write(thumb, "GIF", os); response.setContentType("image/gif"); } try (ServletOutputStream srvos = response.getOutputStream()) { response.setContentLength(os.size()); response.setHeader("Content-Disposition", "inline; filename=\"" + file.getName() + "\""); os.writeTo(srvos); srvos.flush(); } } } } // TODO: check and report success } else { PrintWriter writer = response.getWriter(); writer.write("call POST with multipart form data"); } }
From source file:fr.paris.lutece.plugins.stock.modules.billetterie.web.PosterImageServlet.java
/** * Returns poster image/*from w ww . j a v a 2 s .c om*/ * * @param request the request * @param response the response * @throws ServletException the servlet exception * @throws IOException Signals that an I/O exception has occurred. */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String sIdProduct = request.getParameter(PARAMETER_PRODUCT_ID); if (StringUtils.isNotEmpty(sIdProduct)) { Integer idProduct = Integer.parseInt(sIdProduct); boolean isThumbnail = (request.getParameter(PARAMETER_TB) != null) && request.getParameter(PARAMETER_TB).equals(String.valueOf(true)); byte[] bImage; if (isThumbnail) { bImage = _productService.getTbImage(idProduct); } else { bImage = _productService.getImage(idProduct); } response.setContentLength(bImage.length); response.setContentType(CONTENT_TYPE_IMAGE_JPEG); ServletOutputStream os = response.getOutputStream(); IOUtils.write(bImage, os); os.flush(); os.close(); } else { LOGGER.error(ERROR_MESSAGE); } }
From source file:com.sshdemo.common.report.manage.web.TextReportAction.java
public void download() { PrintWriter pw = null;/*from w w w.j av a 2 s. co m*/ InputStream in = null; try { if (getTextId() != null) { TextReport report = reportFac.findTextReportById(getTextId()); if (report.getTextEntity() != null && report.getTextEntity().length != 0) { String fileName = String.valueOf(report.getName()); fileName = URLEncoder.encode(fileName, "UTF-8"); //fileName = new String(fileName.getBytes("GBK"), "ISO8859-1"); HttpServletResponse response = ServletActionContext.getResponse(); response.setContentType("application/jrxml"); response.setCharacterEncoding("UTF-8"); response.setHeader("Content-disposition", "attachment; filename=" + fileName + ".jrxml"); byte[] bytes = new byte[report.getTextEntity().length]; bytes = report.getTextEntity(); pw = response.getWriter(); response.setContentLength(bytes.length); in = new ByteArrayInputStream(bytes); int len = 0; while ((len = in.read()) > -1) { pw.write(len); } pw.flush(); } else { this.addActionError("?"); } } else { this.addActionError("?"); } } catch (IOException e) { } finally { if (pw != null) { try { pw.close(); pw = null; } catch (Exception e) { } } if (in != null) { try { in.close(); in = null; } catch (Exception e) { } } } }
From source file:de.kp.ames.web.core.service.ServiceImpl.java
public void sendResponse(byte[] bytes, String mimetype, HttpServletResponse response) throws IOException { response.setStatus(HttpServletResponse.SC_OK); response.setCharacterEncoding("UTF-8"); response.setContentType(mimetype);/* w w w. j a v a2 s .c o m*/ response.setContentLength(bytes.length); OutputStream os = response.getOutputStream(); os.write(bytes); os.close(); }
From source file:de.mpg.escidoc.pubman.viewItem.bean.FileBean.java
/** * Sends back an html response of content type text/plain that includes the checksum as UTF-8 string. * @return// w ww . jav a 2 s . co m */ public String displayChecksum() { if (file.getChecksum() != null && file.getChecksumAlgorithm() != null) { FacesContext facesContext = FacesContext.getCurrentInstance(); HttpServletResponse response = (HttpServletResponse) facesContext.getExternalContext().getResponse(); response.setContentLength(file.getChecksum().length()); response.setContentType("text/plain"); try { String filename = this.file.getName(); if (filename != null) { filename = filename.replace(" ", "_"); } else { filename = ""; } response.setHeader("Content-disposition", "attachment; filename=" + URLEncoder.encode(filename, "UTF-8") + "." + getChecksumAlgorithmAsString().toLowerCase()); OutputStream out = response.getOutputStream(); out.write(file.getChecksum().getBytes("UTF-8")); out.flush(); facesContext.responseComplete(); out.close(); } catch (Exception e) { error("Could not display checksum of file!"); logger.error("Could not display checksum of file", e); } return ""; } else { error("Could not display checksum of file!"); logger.error("File checksum is null"); return ""; } }
From source file:it.greenvulcano.gvesb.adapter.http.mapping.RESTHttpServletMapping.java
/** * Sets header fields for file download. * // www. j a v a2 s. c o m * @param resp * An HttpServletResponse object * @param contentType * A string containing the declared response's content type * @param fileName * A string containing the downloaded file name * @param fileSize * A string containing the downloaded file size */ private void setRespDownloadHeaders(HttpServletResponse resp, String contentType, String fileName, int fileSize) { resp.setContentType(contentType); resp.setContentLength(fileSize); resp.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\""); resp.setHeader("Connection", "close"); resp.setHeader("Expires", "-1"); resp.setHeader("Pragma", "no-cache"); resp.setHeader("Cache-Control", "no-cache"); }