Java Code Examples for javax.servlet.http.HttpServletRequest#getPart()

The following examples show how to use javax.servlet.http.HttpServletRequest#getPart() . These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: Tomcat8-Source-Read   File: TestRequest.java    License: MIT License 6 votes vote down vote up
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
    req.setCharacterEncoding("UTF-8");

    if (req.getRequestURI().endsWith("parseParametersBeforeParseParts")) {
        req.getParameterNames();
    }

    req.getPart("part");

    resp.setContentType("text/plain");
    resp.setCharacterEncoding("UTF-8");

    resp.getWriter().println("Part " + req.getParameter("part"));
}
 
Example 2
private static final boolean isCorrectMultipartFormDataContent(final HttpServletRequest request) {
	try {
		final Part part = request.getPart(UNSUBSCRIBE_PARAMETER_NAME);
		
		if(part == null) {
			if(LOGGER.isInfoEnabled()) {
				LOGGER.info(String.format("Multipart message does not contain parameter '%s'", UNSUBSCRIBE_PARAMETER_NAME));
			}
			
			return false;
		}
		
		return isCorrectParameterValue(part);
	} catch(final Exception e) {
		return false;
	}
}
 
Example 3
/**
 * Extracts the file payload from an HttpServletRequest, checks that the file extension
 * is supported and uploads the file to Google Cloud Storage.
 */
public String getImageUrl(HttpServletRequest req, HttpServletResponse resp,
                          final String bucket) throws IOException, ServletException {
  Part filePart = req.getPart("file");
  final String fileName = filePart.getSubmittedFileName();
  String imageUrl = req.getParameter("imageUrl");
  // Check extension of file
  if (fileName != null && !fileName.isEmpty() && fileName.contains(".")) {
    final String extension = fileName.substring(fileName.lastIndexOf('.') + 1);
    String[] allowedExt = {"jpg", "jpeg", "png", "gif"};
    for (String s : allowedExt) {
      if (extension.equals(s)) {
        return this.uploadFile(filePart, bucket);
      }
    }
    throw new ServletException("file must be an image");
  }
  return imageUrl;
}
 
Example 4
/**
 * Unify FileItem and Part instances behind one interface
 */
private WrappedUpload wrapUpload(HttpServletRequest request, String name) {

    FileItem item = (FileItem) request.getAttribute(name);
    if (item != null) {
        return new WrappedUpload(item);
    }

    try {
        Part part = request.getPart(name);
        if (part != null) return new WrappedUpload(part);
    } catch (Exception e) {
        log.error("Failed to get upload part from request. Null will be returned.", e);
    }
    return null;
}
 
Example 5
/**
 * Extracts the file payload from an HttpServletRequest, checks that the file extension
 * is supported and uploads the file to Google Cloud Storage.
 */
public String getImageUrl(HttpServletRequest req, HttpServletResponse resp,
                          final String bucket) throws IOException, ServletException {
  Part filePart = req.getPart("file");
  final String fileName = filePart.getSubmittedFileName();
  String imageUrl = req.getParameter("imageUrl");
  // Check extension of file
  if (fileName != null && !fileName.isEmpty() && fileName.contains(".")) {
    final String extension = fileName.substring(fileName.lastIndexOf('.') + 1);
    String[] allowedExt = {"jpg", "jpeg", "png", "gif"};
    for (String s : allowedExt) {
      if (extension.equals(s)) {
        return this.uploadFile(filePart, bucket);
      }
    }
    throw new ServletException("file must be an image");
  }
  return imageUrl;
}
 
Example 6
Source Project: java-docs-samples   File: UploadServlet.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp)
    throws IOException, ServletException {
  final Part filePart = req.getPart("file");
  final String fileName = filePart.getSubmittedFileName();

  // Modify access list to allow all users with link to read file
  List<Acl> acls = new ArrayList<>();
  acls.add(Acl.of(Acl.User.ofAllUsers(), Acl.Role.READER));
  // the inputstream is closed by default, so we don't need to close it here
  Blob blob =
      storage.create(
          BlobInfo.newBuilder(BUCKET_NAME, fileName).setAcl(acls).build(),
          filePart.getInputStream());

  // return the public download link
  resp.getWriter().print(blob.getMediaLink());
}
 
Example 7
/**
 * Extracts the file payload from an HttpServletRequest, checks that the file extension
 * is supported and uploads the file to Google Cloud Storage.
 */
public String getImageUrl(HttpServletRequest req, HttpServletResponse resp,
                          final String bucket) throws IOException, ServletException {
  Part filePart = req.getPart("file");
  final String fileName = filePart.getSubmittedFileName();
  String imageUrl = req.getParameter("imageUrl");
  // Check extension of file
  if (fileName != null && !fileName.isEmpty() && fileName.contains(".")) {
    final String extension = fileName.substring(fileName.lastIndexOf('.') + 1);
    String[] allowedExt = {"jpg", "jpeg", "png", "gif"};
    for (String s : allowedExt) {
      if (extension.equals(s)) {
        return this.uploadFile(filePart, bucket);
      }
    }
    throw new ServletException("file must be an image");
  }
  return imageUrl;
}
 
Example 8
Source Project: tomcatsrc   File: TestRequest.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
    req.setCharacterEncoding("UTF-8");

    if (req.getRequestURI().endsWith("parseParametersBeforeParseParts")) {
        req.getParameterNames();
    }

    req.getPart("part");

    resp.setContentType("text/plain");
    resp.setCharacterEncoding("UTF-8");

    resp.getWriter().println("Part " + req.getParameter("part"));
}
 
Example 9
Source Project: bidder   File: WebCampaign.java    License: Apache License 2.0 5 votes vote down vote up
public String multiPart(Request baseRequest, HttpServletRequest request, MultipartConfigElement config)
		throws Exception {

	HttpSession session = request.getSession(false);
	String user = (String) session.getAttribute("user");

	baseRequest.setAttribute(Request.__MULTIPART_CONFIG_ELEMENT, config);
	Collection<Part> parts = request.getParts();
	for (Part part : parts) {
		System.out.println("" + part.getName());
	}

	Part filePart = request.getPart("file");

	InputStream imageStream = filePart.getInputStream();
	byte[] resultBuff = new byte[0];
	byte[] buff = new byte[1024];
	int k = -1;
	while ((k = imageStream.read(buff, 0, buff.length)) > -1) {
		byte[] tbuff = new byte[resultBuff.length + k]; // temp buffer size
														// = bytes already
														// read + bytes last
														// read
		System.arraycopy(resultBuff, 0, tbuff, 0, resultBuff.length); // copy
																		// previous
																		// bytes
		System.arraycopy(buff, 0, tbuff, resultBuff.length, k); // copy
																// current
																// lot
		resultBuff = tbuff; // call the temp buffer as your result buff
	}

	Map response = new HashMap();
	return getString(response);

}
 
Example 10
Source Project: quarkus   File: MultipartConfigTestCase.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    Part p = request.getPart("file");
    System.out.println(p.getName());
    response.setStatus(HttpServletResponse.SC_CREATED);
    try (PrintWriter out = response.getWriter()) {
        out.print("OK");
    }
}
 
Example 11
Source Project: boubei-tss   File: Servlet4Upload.java    License: Apache License 2.0 5 votes vote down vote up
protected void doPost(HttpServletRequest request,
		HttpServletResponse response) throws ServletException, IOException {
	
       String servletPath = request.getServletPath() + "";
       if( servletPath.endsWith("/remote/upload") ) { // 远程上传,先校验令牌,通过则进行自动登录
       	Filter8APITokenCheck.checkAPIToken( request );
       }
	
       String script;
	try {
        Part part = request.getPart("file");
		script = doUpload(request, part); // 自定义输出到指定目录
		
	} catch (Exception _e) {
		Exception e = ExceptionConvertorFactory.getConvertor().convert(_e);
		ExceptionEncoder.printErrorMessage(_e);
		
		String errorMsg = "上传(导入)失败:" + e.getMessage();
		errorMsg = Pattern.compile("\t|\r|\n|\'").matcher(errorMsg).replaceAll(" "); // 剔除换行,以免alert不出来
		script = "parent.alert('" + errorMsg + "');";
	} 
	
	script = (String) EasyUtils.checkNull(script, "console.log('上传完成')");
	
	// 上传文件在一个独立的iframe里执行,完成后,输出一个html到该iframe,以触发提示脚本
	response.setContentType("text/html;charset=utf-8");
	response.getWriter().print("<html><script>" +script+ "</script></html>");
}
 
Example 12
Source Project: BLELocalization   File: DataServlet.java    License: MIT License 5 votes vote down vote up
private static Part getPart(HttpServletRequest request, String name) {
	try {
		return request.getPart(name);
	} catch (Exception e) {
		return null;
	}
}
 
Example 13
Source Project: dropbox-sdk-java   File: FormProtection.java    License: MIT License 5 votes vote down vote up
public static String checkAntiCsrfToken(HttpServletRequest request) throws IOException, ServletException
{
    if (request.getContentType() != null &&
        request.getContentType().toLowerCase().indexOf("multipart/form-data") > -1 &&
        request.getPart("anti-csrf-token") == null ||
        request.getParameter("anti-csrf-token") == null) {
        return "missing \"" + antiCsrfTokenName + "\" POST parameter";
    }

    // SECURITY TODO: Actually validate anti-CSRF token.
    return null;
}
 
Example 14
@Override
public String handleRequest(HttpServletRequest request, BindingResult result, Wizard wizard) {
  ImportWizardUtil.validateImportWizard(wizard);
  ImportWizard importWizard = (ImportWizard) wizard;
  String dataImportOption = request.getParameter("data-option");

  try {
    File file = null;
    Part part = request.getPart("upload");
    if (part != null) {
      file = FileUploadUtils.saveToTempFolder(part);
    }

    if (file == null) {
      result.addError(new ObjectError("wizard", "No file selected"));
    } else {
      importWizard.setFile(file);

      RepositoryCollection repositoryCollection =
          getFileRepositoryCollectionFactory().createFileRepositoryCollection(file);
      ImportService importService =
          getImportServiceFactory().getImportService(file, repositoryCollection);

      importWizard.setSupportedMetadataActions(importService.getSupportedMetadataActions());
      importWizard.setSupportedDataActions(importService.getSupportedDataActions());
      importWizard.setMustChangeEntityName(importService.getMustChangeEntityName());
    }

  } catch (Exception e) {
    ImportWizardUtil.handleException(e, importWizard, result, LOG, dataImportOption);
  }

  return null;
}
 
Example 15
Source Project: Tomcat8-Source-Read   File: HTMLManagerServlet.java    License: MIT License 4 votes vote down vote up
protected String upload(HttpServletRequest request, StringManager smClient) {
    String message = "";

    try {
        while (true) {
            Part warPart = request.getPart("deployWar");
            if (warPart == null) {
                message = smClient.getString(
                        "htmlManagerServlet.deployUploadNoFile");
                break;
            }
            String filename = warPart.getSubmittedFileName();
            if (!filename.toLowerCase(Locale.ENGLISH).endsWith(".war")) {
                message = smClient.getString(
                        "htmlManagerServlet.deployUploadNotWar", filename);
                break;
            }
            // Get the filename if uploaded name includes a path
            if (filename.lastIndexOf('\\') >= 0) {
                filename =
                    filename.substring(filename.lastIndexOf('\\') + 1);
            }
            if (filename.lastIndexOf('/') >= 0) {
                filename =
                    filename.substring(filename.lastIndexOf('/') + 1);
            }

            // Identify the appBase of the owning Host of this Context
            // (if any)
            File file = new File(host.getAppBaseFile(), filename);
            if (file.exists()) {
                message = smClient.getString(
                        "htmlManagerServlet.deployUploadWarExists",
                        filename);
                break;
            }

            ContextName cn = new ContextName(filename, true);
            String name = cn.getName();

            if ((host.findChild(name) != null) && !isDeployed(name)) {
                message = smClient.getString(
                        "htmlManagerServlet.deployUploadInServerXml",
                        filename);
                break;
            }

            if (isServiced(name)) {
                message = smClient.getString("managerServlet.inService", name);
            } else {
                addServiced(name);
                try {
                    warPart.write(file.getAbsolutePath());
                    // Perform new deployment
                    check(name);
                } finally {
                    removeServiced(name);
                }
            }
            break;
        }
    } catch(Exception e) {
        message = smClient.getString
            ("htmlManagerServlet.deployUploadFail", e.getMessage());
        log(message, e);
    }
    return message;
}
 
Example 16
Source Project: BLELocalization   File: ImportServlet.java    License: MIT License 4 votes vote down vote up
/**
 * @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();
		}
	}
}
 
Example 17
@Nullable
public static Object resolveMultipartArgument(String name, MethodParameter parameter, HttpServletRequest request)
		throws Exception {

	MultipartHttpServletRequest multipartRequest =
			WebUtils.getNativeRequest(request, MultipartHttpServletRequest.class);
	boolean isMultipart = (multipartRequest != null || isMultipartContent(request));

	if (MultipartFile.class == parameter.getNestedParameterType()) {
		if (multipartRequest == null && isMultipart) {
			multipartRequest = new StandardMultipartHttpServletRequest(request);
		}
		return (multipartRequest != null ? multipartRequest.getFile(name) : null);
	}
	else if (isMultipartFileCollection(parameter)) {
		if (multipartRequest == null && isMultipart) {
			multipartRequest = new StandardMultipartHttpServletRequest(request);
		}
		return (multipartRequest != null ? multipartRequest.getFiles(name) : null);
	}
	else if (isMultipartFileArray(parameter)) {
		if (multipartRequest == null && isMultipart) {
			multipartRequest = new StandardMultipartHttpServletRequest(request);
		}
		if (multipartRequest != null) {
			List<MultipartFile> multipartFiles = multipartRequest.getFiles(name);
			return multipartFiles.toArray(new MultipartFile[0]);
		}
		else {
			return null;
		}
	}
	else if (Part.class == parameter.getNestedParameterType()) {
		return (isMultipart ? request.getPart(name): null);
	}
	else if (isPartCollection(parameter)) {
		return (isMultipart ? resolvePartList(request, name) : null);
	}
	else if (isPartArray(parameter)) {
		return (isMultipart ? resolvePartList(request, name).toArray(new Part[0]) : null);
	}
	else {
		return UNRESOLVABLE;
	}
}
 
Example 18
Source Project: Tomcat7.0.67   File: HTMLManagerServlet.java    License: Apache License 2.0 4 votes vote down vote up
protected String upload(HttpServletRequest request, StringManager smClient) {
    String message = "";

    try {
        while (true) {
            Part warPart = request.getPart("deployWar");
            if (warPart == null) {
                message = smClient.getString(
                        "htmlManagerServlet.deployUploadNoFile");
                break;
            }
            String filename =
                extractFilename(warPart.getHeader("Content-Disposition"));
            if (!filename.toLowerCase(Locale.ENGLISH).endsWith(".war")) {
                message = smClient.getString(
                        "htmlManagerServlet.deployUploadNotWar", filename);
                break;
            }
            // Get the filename if uploaded name includes a path
            if (filename.lastIndexOf('\\') >= 0) {
                filename =
                    filename.substring(filename.lastIndexOf('\\') + 1);
            }
            if (filename.lastIndexOf('/') >= 0) {
                filename =
                    filename.substring(filename.lastIndexOf('/') + 1);
            }

            // Identify the appBase of the owning Host of this Context
            // (if any)
            File file = new File(deployed, filename);
            if (file.exists()) {
                message = smClient.getString(
                        "htmlManagerServlet.deployUploadWarExists",
                        filename);
                break;
            }
            
            ContextName cn = new ContextName(filename, true);
            String name = cn.getName();

            if ((host.findChild(name) != null) && !isDeployed(name)) {
                message = smClient.getString(
                        "htmlManagerServlet.deployUploadInServerXml",
                        filename);
                break;
            }

            if (isServiced(name)) {
                message = smClient.getString("managerServlet.inService", name);
            } else {
                addServiced(name);
                try {
                    warPart.write(file.getAbsolutePath());
                    // Perform new deployment
                    check(name);
                } finally {
                    removeServiced(name);
                }
            }
            break;
        }
    } catch(Exception e) {
        message = smClient.getString
            ("htmlManagerServlet.deployUploadFail", e.getMessage());
        log(message, e);
    }
    return message;
}
 
Example 19
public static Object resolvePart(HttpServletRequest servletRequest, String name) throws Exception {
	return servletRequest.getPart(name);
}
 
Example 20
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	PageStats.page(request);
	request.setCharacterEncoding("utf-8");
	response.setCharacterEncoding("utf-8");
	
	LoginBean loginBean = (LoginBean)request.getSession().getAttribute("loginBean");
	if (loginBean == null) {
		response.sendRedirect("index.jsp");
		return;
	}
	BotBean botBean = loginBean.getBotBean();
	MemoryBean bean = loginBean.getBean(MemoryBean.class);
	try {
		String postToken = (String)request.getParameter("postToken");
		loginBean.verifyPostToken(postToken);
		String instance = (String)request.getParameter("instance");
		if (instance != null) {
			if (botBean.getInstance() == null || !String.valueOf(botBean.getInstanceId()).equals(instance)) {
				botBean.validateInstance(instance);
			}
		}
		if (!botBean.isConnected()) {
			request.getRequestDispatcher("memory.jsp").forward(request, response);
			return;
		}
		botBean.checkAdmin();
		String importFormat = (String)request.getParameter("import-format");
		String encoding = (String)request.getParameter("import-encoding");
		String pin = (String)request.getParameter("pin");
		Part filePart = request.getPart("file");
		if ((filePart != null) && (filePart.getSize() > 0)) {
			if (filePart.getContentType() != null && filePart.getContentType().equals("csv")) {
				importFormat = "csv";
			}
			String fileName = getFileName(filePart);
			InputStream stream = filePart.getInputStream();
			bean.importFile(fileName, stream, importFormat, encoding, "on".equals(pin));
		} else {
			throw new BotException("Missing file");
		}
		request.getRequestDispatcher("memory.jsp").forward(request, response);
	} catch (Exception failed) {
		botBean.error(failed);
		request.getRequestDispatcher("memory.jsp").forward(request, response);
	}
}