Java Code Examples for javax.servlet.http.HttpServletRequest#getContentLength()
The following examples show how to use
javax.servlet.http.HttpServletRequest#getContentLength() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Pub_WebUtils.java From SuperBoot with MIT License | 7 votes |
/** * 描述:获取 post 请求的 byte[] 数组 * <pre> * 举例: * </pre> * * @param request * @return * @throws IOException */ public static byte[] getRequestPostBytes(HttpServletRequest request) throws IOException { int contentLength = request.getContentLength(); if (contentLength < 0) { return null; } byte buffer[] = new byte[contentLength]; for (int i = 0; i < contentLength; ) { int readlen = request.getInputStream().read(buffer, i, contentLength - i); if (readlen == -1) { break; } i += readlen; } return buffer; }
Example 2
Source File: WebUtil.java From blade-tool with GNU Lesser General Public License v3.0 | 6 votes |
/** * 获取 request 请求的 byte[] 数组 * * @param request request * @return byte[] * @throws IOException IOException */ public static byte[] getRequestBytes(HttpServletRequest request) throws IOException { int contentLength = request.getContentLength(); if (contentLength < 0) { return null; } byte[] buffer = new byte[contentLength]; for (int i = 0; i < contentLength; ) { int readlen = request.getInputStream().read(buffer, i, contentLength - i); if (readlen == -1) { break; } i += readlen; } return buffer; }
Example 3
Source File: ProxyServlet.java From logbook-kai with MIT License | 6 votes |
/** * retryEnabled の時だけだよ * @return */ private ContentProvider createRetryContentProvider() { final HttpServletRequest request = this.request; return new InputStreamContentProvider( new SequenceInputStream(new ByteArrayInputStream(this.contentBuffer.toByteArray()), this.contentInputStream)) { @Override public long getLength() { return request.getContentLength(); } @Override protected ByteBuffer onRead(byte[] buffer, int offset, int length) { if (ProxyServlet.this._isDebugEnabled) { ProxyServlet.this._log .debug("{} proxying content to upstream: {} bytes", getRequestId(request), length); } return super.onRead(buffer, offset, length); } }; }
Example 4
Source File: WebUtil.java From magic-starter with GNU Lesser General Public License v3.0 | 6 votes |
/** * 获取 request 请求的 byte[] 数组 * * @param request request * @return byte[] * @throws IOException IOException */ public static byte[] getRequestBytes(HttpServletRequest request) throws IOException { int contentLength = request.getContentLength(); if (contentLength < 0) { return null; } byte[] buffer = new byte[contentLength]; for (int i = 0; i < contentLength; ) { int readlen = request.getInputStream().read(buffer, i, contentLength - i); if (readlen == -1) { break; } i += readlen; } return buffer; }
Example 5
Source File: ProxyController.java From FATE-Serving with Apache License 2.0 | 5 votes |
String binaryReader(HttpServletRequest request) throws IOException { int len = request.getContentLength(); ServletInputStream iii = request.getInputStream(); byte[] buffer = new byte[len]; iii.read(buffer, 0, len); return new String(buffer); }
Example 6
Source File: UploadAtt.java From NutzCodematic with Apache License 2.0 | 5 votes |
public boolean uploadFile( HttpServletRequest req) throws ServletException, IOException{ setCharacterEncoding(req.getCharacterEncoding()); setContentType(req.getContentType()); m_totalBytes = req.getContentLength(); if(!(m_totalBytes>maxSize)) { uploadFile(req.getInputStream()); return true; } else { return false; } }
Example 7
Source File: LittleTsaService.java From littleca with Apache License 2.0 | 5 votes |
private TimeStampRequest readRequest(HttpServletRequest req, boolean isBase64) throws Exception { byte[] requestBytes = new byte[req.getContentLength()]; ServletInputStream inputStream = req.getInputStream(); IOUtils.read(inputStream, requestBytes); if (isBase64) { return new TimeStampRequest(Base64.decode(requestBytes)); } else { return new TimeStampRequest(requestBytes); } }
Example 8
Source File: ServletServerHttpRequest.java From java-technology-stack with MIT License | 5 votes |
private static HttpHeaders initHeaders(HttpHeaders headers, HttpServletRequest request) { MediaType contentType = headers.getContentType(); if (contentType == null) { String requestContentType = request.getContentType(); if (StringUtils.hasLength(requestContentType)) { contentType = MediaType.parseMediaType(requestContentType); headers.setContentType(contentType); } } if (contentType != null && contentType.getCharset() == null) { String encoding = request.getCharacterEncoding(); if (StringUtils.hasLength(encoding)) { Charset charset = Charset.forName(encoding); Map<String, String> params = new LinkedCaseInsensitiveMap<>(); params.putAll(contentType.getParameters()); params.put("charset", charset.toString()); headers.setContentType( new MediaType(contentType.getType(), contentType.getSubtype(), params)); } } if (headers.getContentLength() == -1) { int contentLength = request.getContentLength(); if (contentLength != -1) { headers.setContentLength(contentLength); } } return headers; }
Example 9
Source File: ContentCachingRequestWrapper.java From java-technology-stack with MIT License | 5 votes |
/** * Create a new ContentCachingRequestWrapper for the given servlet request. * @param request the original servlet request */ public ContentCachingRequestWrapper(HttpServletRequest request) { super(request); int contentLength = request.getContentLength(); this.cachedContent = new ByteArrayOutputStream(contentLength >= 0 ? contentLength : 1024); this.contentCacheLimit = null; }
Example 10
Source File: HttpServletRequestSnapshot.java From cxf with Apache License 2.0 | 5 votes |
public HttpServletRequestSnapshot(HttpServletRequest request) { super(request); authType = request.getAuthType(); characterEncoding = request.getCharacterEncoding(); contentLength = request.getContentLength(); contentType = request.getContentType(); contextPath = request.getContextPath(); cookies = request.getCookies(); requestHeaderNames = request.getHeaderNames(); Enumeration<String> tmp = request.getHeaderNames(); while (tmp.hasMoreElements()) { String key = tmp.nextElement(); headersMap.put(key, request.getHeaders(key)); } localAddr = request.getLocalAddr(); local = request.getLocale(); localName = request.getLocalName(); localPort = request.getLocalPort(); method = request.getMethod(); pathInfo = request.getPathInfo(); pathTranslated = request.getPathTranslated(); protocol = request.getProtocol(); queryString = request.getQueryString(); remoteAddr = request.getRemoteAddr(); remoteHost = request.getRemoteHost(); remotePort = request.getRemotePort(); remoteUser = request.getRemoteUser(); requestURI = request.getRequestURI(); requestURL = request.getRequestURL(); requestedSessionId = request.getRequestedSessionId(); schema = request.getScheme(); serverName = request.getServerName(); serverPort = request.getServerPort(); servletPath = request.getServletPath(); if (request.isRequestedSessionIdValid()) { session = request.getSession(); } principal = request.getUserPrincipal(); }
Example 11
Source File: RequestLabelsHelper.java From cloud-trace-java with Apache License 2.0 | 5 votes |
/** * Adds span label annotations based on the given HTTP servlet request to the given labels * builder. * * @param request the http servlet request used to generate the span label annotations. * @param labelsBuilder the labels builder to add span label annotations to. */ public static void addRequestLabels(HttpServletRequest request, Labels.Builder labelsBuilder) { labelsBuilder.add("/http/method", request.getMethod()); labelsBuilder.add("/http/url", request.getRequestURL().toString()); if (request.getContentLength() != -1) { labelsBuilder.add( "/http/request/size", Integer.toString(request.getContentLength())); } labelsBuilder.add("/http/host", request.getServerName()); if (request.getHeader("user-agent") != null) { labelsBuilder.add("/http/user_agent", request.getHeader("user-agent")); } }
Example 12
Source File: HttpEndpoint.java From spring-integration-aws with MIT License | 5 votes |
private String readBody(HttpServletRequest request) throws IOException { StringBuilder buffer = new StringBuilder(request.getContentLength()); String line = null; BufferedReader reader = request.getReader(); while ((line = reader.readLine()) != null) { buffer.append(line); } return buffer.toString(); }
Example 13
Source File: LoggingFilter.java From brooklyn-server with Apache License 2.0 | 4 votes |
private String getRequestCompletedMessage(boolean includeHeaders, Duration elapsed, String id, HttpServletRequest httpRequest, HttpServletResponse httpResponse) { StringBuilder message = new StringBuilder("Request ") .append(id) .append(" completed in ") .append(elapsed) .append(": response ") .append(httpResponse.getStatus()) .append(" for ") .append(httpRequest.getMethod()) .append(" ") .append(httpRequest.getRequestURI()) .append(" from ") .append(httpRequest.getRemoteAddr()); if (!httpRequest.getParameterMap().isEmpty()) { message.append(", parameters: ") .append(Joiner.on(", ").withKeyValueSeparator("=").join(httpRequest.getParameterMap())); } if (httpRequest.getContentLength() > 0) { int len = httpRequest.getContentLength(); message.append(" contentType=").append(httpRequest.getContentType()) .append(" (length=").append(len).append(")"); } if (includeHeaders) { Enumeration<String> headerNames = httpRequest.getHeaderNames(); if (headerNames.hasMoreElements()) { message.append(", headers: "); while (headerNames.hasMoreElements()) { String headerName = headerNames.nextElement(); message.append(headerName).append(": "); if (CENSORED_HEADERS.contains(headerName)) { message.append("******"); } else { message.append(httpRequest.getHeader(headerName)); } if (headerNames.hasMoreElements()) { message.append(", "); } } } } return message.toString(); }
Example 14
Source File: RestServlet.java From mdw with Apache License 2.0 | 4 votes |
protected String handleRequest(HttpServletRequest request, HttpServletResponse response, Map<String,String> metaInfo) throws ServiceException, IOException { if (logger.isMdwDebugEnabled()) { logger.mdwDebug(getClass().getSimpleName() + " " + request.getMethod() + ":\n " + request.getRequestURI() + (request.getQueryString() == null ? "" : ("?" + request.getQueryString()))); } String requestString = null; // DELETE can have a body in some containers if (!"GET".equalsIgnoreCase(request.getMethod())) { BufferedReader reader = request.getReader(); StringBuffer requestBuffer = new StringBuffer(request.getContentLength() < 0 ? 0 : request.getContentLength()); String line; while ((line = reader.readLine()) != null) requestBuffer.append(line).append('\n'); // log request requestString = requestBuffer.toString(); if (logger.isMdwDebugEnabled()) { logger.mdwDebug(getClass().getSimpleName() + " " + request.getMethod() + " Request:\n" + requestString); } } authenticate(request, metaInfo, requestString); if (metaInfo.containsKey(Listener.METAINFO_REQUEST_PAYLOAD)) { requestString = metaInfo.get(Listener.METAINFO_REQUEST_PAYLOAD); metaInfo.remove(Listener.METAINFO_REQUEST_PAYLOAD); } Set<String> reqHeaderKeys = new HashSet<>(metaInfo.keySet()); String responseString = new ListenerHelper().processRequest(requestString, metaInfo); populateResponseHeaders(reqHeaderKeys, metaInfo, response); if (metaInfo.get(Listener.METAINFO_CONTENT_TYPE) == null) response.setContentType("application/json"); else response.setContentType(metaInfo.get(Listener.METAINFO_CONTENT_TYPE)); if (metaInfo.get(Listener.METAINFO_HTTP_STATUS_CODE) != null && !metaInfo.get(Listener.METAINFO_HTTP_STATUS_CODE).equals("0")) response.setStatus(Integer.parseInt(metaInfo.get(Listener.METAINFO_HTTP_STATUS_CODE))); if (logger.isMdwDebugEnabled()) { logger.mdwDebug(getClass().getSimpleName() + " " + request.getMethod() + " Response:\n" + responseString); } return responseString; }
Example 15
Source File: UploadUtils.java From jeecg with Apache License 2.0 | 4 votes |
/** * 上传验证,并初始化文件目录 * * @param request */ private String validateFields(HttpServletRequest request) { String errorInfo = "true"; // boolean errorFlag = true; // 获取内容类型 String contentType = request.getContentType(); int contentLength = request.getContentLength(); // 文件保存目录路径 savePath = request.getSession().getServletContext().getRealPath("/") + basePath + "/"; // 文件保存目录URL saveUrl = request.getContextPath() + "/" + basePath + "/"; File uploadDir = new File(savePath); if (contentType == null || !contentType.startsWith("multipart")) { // TODO org.jeecgframework.core.util.LogUtil.info("请求不包含multipart/form-data流"); errorInfo = "请求不包含multipart/form-data流"; } else if (maxSize < contentLength) { // TODO org.jeecgframework.core.util.LogUtil.info("上传文件大小超出文件最大大小"); errorInfo = "上传文件大小超出文件最大大小[" + maxSize + "]"; } else if (!ServletFileUpload.isMultipartContent(request)) { // TODO errorInfo = "请选择文件"; } else if (!uploadDir.isDirectory()) {// 检查目录 // TODO errorInfo = "上传目录[" + savePath + "]不存在"; } else if (!uploadDir.canWrite()) { // TODO errorInfo = "上传目录[" + savePath + "]没有写权限"; } else if (!extMap.containsKey(dirName)) { // TODO errorInfo = "目录名不正确"; } else { // .../basePath/dirName/ // 创建文件夹 savePath += dirName + "/"; saveUrl += dirName + "/"; File saveDirFile = new File(savePath); if (!saveDirFile.exists()) { saveDirFile.mkdirs(); } // .../basePath/dirName/yyyyMMdd/ SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd"); String ymd = sdf.format(new Date()); savePath += ymd + "/"; saveUrl += ymd + "/"; File dirFile = new File(savePath); if (!dirFile.exists()) { dirFile.mkdirs(); } // 获取上传临时路径 tempPath = request.getSession().getServletContext().getRealPath("/") + tempPath + "/"; File file = new File(tempPath); if (!file.exists()) { file.mkdirs(); } } return errorInfo; }
Example 16
Source File: LittleTsaService.java From littleca with Apache License 2.0 | 4 votes |
@RequestMapping(value = "tsa", method = RequestMethod.POST) public void tsa(HttpServletRequest req, HttpServletResponse resp) { String remoteIp = req.getRemoteAddr(); try { if (!TsaTranserConstant.TIMESTAMP_QUERY_CONTENT_TYPE.equalsIgnoreCase(req.getContentType())) { resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "content type should be " + TsaTranserConstant.TIMESTAMP_QUERY_CONTENT_TYPE); return; } if (!TsaTranserConstant.TIMESTAMP_QUERY_CONTENT_TYPE.equalsIgnoreCase(req.getContentType())) { resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "content type should be " + TsaTranserConstant.TIMESTAMP_QUERY_CONTENT_TYPE); return; } if (littleTsaConfig.isUsernameEnabled()) { if (!littleTsaConfig.getTsaUsername().equals(req.getHeader("username")) || !littleTsaConfig.getTsaPassword().equals(req.getHeader("password"))) { resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "username and password must match"); return; } } if (req.getContentLength() == 0) { LOG.error("timestamp request is empty"); resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "timestamp request is empty"); return; } boolean isBase64 = TsaTranserConstant.isBase64(req.getHeader(TsaTranserConstant.TRANSFER_ENCODING_HEADER)); TimeStampRequest timeStampRequest = readRequest(req, isBase64); LOG.debug("TS Request received from {}", remoteIp); TimeStampResponse stampResponse = timeStampService.timestamp(timeStampRequest); if (stampResponse == null) { LOG.warn("TS Request received from {} is not acceptable", remoteIp); resp.sendError(HttpServletResponse.SC_NOT_ACCEPTABLE, "Could not generate timestamp response"); return; } if (stampResponse.getTimeStampToken() == null) { LOG.warn("TS Request received from {} is not acceptable", remoteIp); resp.sendError(HttpServletResponse.SC_NOT_ACCEPTABLE, "Could not generate timestamp response"); return; } byte[] response = stampResponse.getEncoded(); if (isBase64) { resp.setHeader(TsaTranserConstant.TRANSFER_ENCODING_HEADER, TsaTranserConstant.TRANSFER_ENCODING_BASE64); response = Base64.encode(response); LOG.debug("Responding to {} is in base64", remoteIp); } else { resp.setHeader(TsaTranserConstant.TRANSFER_ENCODING_HEADER, TsaTranserConstant.TRANSFER_ENCODING_BINARY); LOG.debug("Responding to %s is in binary mode", remoteIp); } resp.setStatus(HttpServletResponse.SC_OK); resp.setContentType(TsaTranserConstant.TIMESTAMP_REPLY_CONTENT_TYPE); resp.setContentLength(response.length); ServletOutputStream outputStream = resp.getOutputStream(); outputStream.write(response); outputStream.close(); } catch (Exception e) { LOG.warn("TS Request received from {} is not acceptable", remoteIp); try { resp.sendError(HttpServletResponse.SC_NOT_ACCEPTABLE, "Could not generate timestamp response"); } catch (IOException ex) { LOG.error("error,{}", ex); } } }
Example 17
Source File: GalleryServlet.java From appinventor-extensions with Apache License 2.0 | 4 votes |
@Override public void doPost(HttpServletRequest req, HttpServletResponse resp) { setDefaultHeader(resp); UploadResponse uploadResponse; String uri = req.getRequestURI(); // First, call split with no limit parameter. String[] uriComponents = uri.split("/"); if (true) { String requestType = uriComponents[REQUEST_TYPE_INDEX]; if (DEBUG) { LOG.info("######### GOT IN URI"); LOG.info(requestType); } long project_Id = -1; String user_Id = "-1"; if (requestType.equalsIgnoreCase("apps")) { project_Id = Long.parseLong(uriComponents[GALLERY_OR_USER_ID_INDEX]); } else if (requestType.equalsIgnoreCase("user")) { //the code below doesn't check if user_Id is the id of current user //user_Id = uriComponents[GALLERY_OR_USER_ID_INDEX]; user_Id = userInfoProvider.getUserId(); } InputStream uploadedStream; try { if(req.getContentLength() < MAX_IMAGE_FILE_SIZE){ uploadedStream = getRequestStream(req, ServerLayout.UPLOAD_FILE_FORM_ELEMENT); // Converts the input stream to byte array byte[] buffer = new byte[8000]; int bytesRead = 0; ByteArrayOutputStream bao = new ByteArrayOutputStream(); while ((bytesRead = uploadedStream.read(buffer)) != -1) { bao.write(buffer, 0, bytesRead); } // Set up the cloud file (options) String key = ""; GallerySettings settings = galleryService.loadGallerySettings(); if (requestType.equalsIgnoreCase("apps")) { key = settings.getProjectImageKey(project_Id); } else if (requestType.equalsIgnoreCase("user")) { key = settings.getUserImageKey(user_Id); } // setup cloud GcsService gcsService = GcsServiceFactory.createGcsService(); GcsFilename filename = new GcsFilename(settings.getBucket(), key); GcsFileOptions options = new GcsFileOptions.Builder().mimeType("image/jpeg") .acl("public-read").cacheControl("no-cache").build(); GcsOutputChannel writeChannel = gcsService.createOrReplace(filename, options); writeChannel.write(ByteBuffer.wrap(bao.toByteArray())); // Now finalize writeChannel.close(); uploadResponse = new UploadResponse(UploadResponse.Status.SUCCESS); }else{ /*file exceeds size of MAX_IMAGE_FILE_SIZE*/ uploadResponse = new UploadResponse(UploadResponse.Status.FILE_TOO_LARGE); } // Now, get the PrintWriter for the servlet response and print the UploadResponse. // On the client side, in the onSubmitComplete method in ode/client/utils/Uploader.java, the // UploadResponse value will be retrieved as a String via the // FormSubmitCompleteEvent.getResults() method. PrintWriter out = resp.getWriter(); out.print(uploadResponse.formatAsHtml()); } catch (Exception e) { throw CrashReport.createAndLogError(LOG, req, null, e); } // Set http response information resp.setStatus(HttpServletResponse.SC_OK); } // Now, get the PrintWriter for the servlet response and print the UploadResponse. // On the client side, in the onSubmitComplete method in ode/client/utils/Uploader.java, the // UploadResponse value will be retrieved as a String via the // FormSubmitCompleteEvent.getResults() method. // PrintWriter out = resp.getWriter(); // out.print(uploadResponse.formatAsHtml()); // Set http response information resp.setStatus(HttpServletResponse.SC_OK); }
Example 18
Source File: UploadUtils.java From jeewx with Apache License 2.0 | 4 votes |
/** * 上传验证,并初始化文件目录 * * @param request */ private String validateFields(HttpServletRequest request) { String errorInfo = "true"; // boolean errorFlag = true; // 获取内容类型 String contentType = request.getContentType(); int contentLength = request.getContentLength(); // 文件保存目录路径 savePath = request.getSession().getServletContext().getRealPath("/") + basePath + "/"; // 文件保存目录URL saveUrl = request.getContextPath() + "/" + basePath + "/"; File uploadDir = new File(savePath); if (contentType == null || !contentType.startsWith("multipart")) { // TODO org.jeecgframework.core.util.LogUtil.info("请求不包含multipart/form-data流"); errorInfo = "请求不包含multipart/form-data流"; } else if (maxSize < contentLength) { // TODO org.jeecgframework.core.util.LogUtil.info("上传文件大小超出文件最大大小"); errorInfo = "上传文件大小超出文件最大大小[" + maxSize + "]"; } else if (!ServletFileUpload.isMultipartContent(request)) { // TODO errorInfo = "请选择文件"; } else if (!uploadDir.isDirectory()) {// 检查目录 // TODO errorInfo = "上传目录[" + savePath + "]不存在"; } else if (!uploadDir.canWrite()) { // TODO errorInfo = "上传目录[" + savePath + "]没有写权限"; } else if (!extMap.containsKey(dirName)) { // TODO errorInfo = "目录名不正确"; } else { // .../basePath/dirName/ // 创建文件夹 savePath += dirName + "/"; saveUrl += dirName + "/"; File saveDirFile = new File(savePath); if (!saveDirFile.exists()) { saveDirFile.mkdirs(); } // .../basePath/dirName/yyyyMMdd/ SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd"); String ymd = sdf.format(new Date()); savePath += ymd + "/"; saveUrl += ymd + "/"; File dirFile = new File(savePath); if (!dirFile.exists()) { dirFile.mkdirs(); } // 获取上传临时路径 tempPath = request.getSession().getServletContext().getRealPath("/") + tempPath + "/"; File file = new File(tempPath); if (!file.exists()) { file.mkdirs(); } } return errorInfo; }
Example 19
Source File: ParsedHttpRequest.java From reef with Apache License 2.0 | 4 votes |
/** * parse HttpServletRequest. * * @param request * @throws IOException */ public ParsedHttpRequest(final HttpServletRequest request) throws IOException { this.pathInfo = request.getPathInfo() != null ? request.getPathInfo() : ""; this.method = request.getMethod() != null ? request.getMethod() : ""; this.queryString = request.getQueryString() != null ? request.getQueryString() : ""; this.requestUri = request.getRequestURI() != null ? request.getRequestURI() : ""; this.requestUrl = request.getRequestURL().toString(); for (final Enumeration en = request.getHeaderNames(); en.hasMoreElements();) { final String headerName = en.nextElement().toString(); this.headers.put(headerName, request.getHeader(headerName)); } final int len = request.getContentLength(); if (len > 0) { this.inputStream = new byte[len]; request.getInputStream().read(this.inputStream); } else { this.inputStream = new byte[0]; } final String[] parts = this.requestUri.split("/"); this.targetSpecification = parts.length > 1 ? parts[1] : null; this.version = parts.length > 2 ? parts[2] : null; this.targetEntity = parts.length > 3 ? parts[3] : null; if (!this.queryString.isEmpty()) { final String[] pairs = this.queryString.split("&"); for (final String pair : pairs) { final int idx = pair.indexOf("="); if (idx != -1) { final String rKey = pair.substring(0, idx); final String rValue = pair.substring(idx + 1); final String key = URLDecoder.decode(rKey, "UTF-8"); final String value = URLDecoder.decode(rValue, "UTF-8"); List<String> valuesList = this.queryPairs.get(key.toLowerCase()); if (valuesList == null) { valuesList = new ArrayList<>(1); this.queryPairs.put(key, valuesList); } valuesList.add(value); } } } }
Example 20
Source File: ImportServlet.java From BLELocalization with MIT License | 4 votes |
/** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse * response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { InputStream is = null; OutputStream os = null; try { Part part = null; try { part = request.getPart("file"); } catch (Exception e) { } String contentType = null; int contentLength = -1; if (part == null) { is = request.getInputStream(); contentType = request.getContentType(); contentLength = request.getContentLength(); } else { is = part.getInputStream(); contentType = part.getContentType(); contentLength = (int) part.getSize(); } response.addHeader("Access-Control-Allow-Origin", "*"); if (contentType != null) { response.setContentType(contentType); } if (contentLength > 0) { response.setContentLength(contentLength); } os = response.getOutputStream(); byte data[] = new byte[4096]; int len = 0; while ((len = is.read(data, 0, data.length)) > 0) { os.write(data, 0, len); } os.flush(); } finally { if (is != null) { is.close(); } if (os != null) { os.close(); } } }