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

The following are Jave code examples for showing how to use getPart() of the javax.servlet.http.HttpServletRequest class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: tomcat7   File: TestRequest.java   View Source Code Vote up 7 votes
@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
Project: kronometer   File: UploadFile.java   View Source Code Vote up 6 votes
/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/plain");
    response.setCharacterEncoding("UTF-8");
    
    String templateName = request.getParameter("demo_name");
    Part filePart = request.getPart("demo_img");
    try{
        // String fileName = Paths.get(filePart.getSubmittedFileName()).getFileName().toString(); // MSIE fix.
        InputStream fileContent = filePart.getInputStream();
        System.out.println(templateName);
        File file = new File("uploads/"+templateName+".png");
        System.out.println(file.getAbsolutePath());
        OutputStream outputStream = new FileOutputStream(file);
        IOUtils.copy(fileContent, outputStream);
        outputStream.close();
        
        Thumbnails.of(new File("uploads/"+templateName+".png"))
        .size(500, 707)
        .outputFormat("PNG")
        .toFiles(Rename.NO_CHANGE);
        
    }catch(NullPointerException ex){
        System.out.println("null param");
    }
    
    response.getWriter().write("uploaded lmao");  
    
    System.out.println("fking shit");
    response.sendRedirect("init.jsp?req="+templateName);
}
 
Example 3
Project: apache-tomcat-7.0.73-with-comment   File: TestRequest.java   View Source Code Vote up 6 votes
@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 4
Project: Hi-Framework   File: FrontiersReqHandler.java   View Source Code Vote up 5 votes
private Object getUploadedFiles(String strParamValue, String frontier, FrontierMethod frontierMethod,
                               MethodParam methodParam, Map<String,Object> uploadsMap,
                                HttpServletRequest request) throws FrontierCallException {

    String uploadName = strParamValue.substring(strParamValue.indexOf(":")+1,strParamValue.length());
    if(!uploadsMap.containsKey(uploadName))
        throw new FrontierCallException(frontier,methodParam.getName(),"The upload request data is corrupted");

    Double totalD = (Double) uploadsMap.get(uploadName);
    int total = totalD.intValue();
    if(total<1)
        throw new MissingFrontierParamException(frontier,frontierMethod.getName(),methodParam.getName());

    FileUpload[] files = new FileUpload[total];
    for(int i=0; i<total;i++){
        try {
            String partName = uploadName + "_file_" + i;
            Part part = request.getPart(partName);
            if (part == null)
                throw new FrontierCallException(frontier, methodParam.getName(), "The upload request data is corrupted");
            files[i] = new FileUpload(part);
        }catch (IOException | ServletException ex){
            throw new FrontierCallException(frontier, methodParam.getName(), "Failed to decode uploaded content",ex);
        }
    }

    if(methodParam.getType().isArray())return files;
    else{

        if(files.length>1)
            throw new FrontierCallException(frontier,methodParam.getName(),"One file expected. "+files.length+" uploaded files found");
        return files[0];

    }

}
 
Example 5
Project: Hi-Framework   File: FrontiersReqHandler.java   View Source Code Vote up 5 votes
private void handleMultipartForm(HttpServletRequest req, String frontier, FrontierMethod frontierMethod,
                                 Map paramsMap) throws FrontierCallException{

    try {

        Part uploadsPart = req.getPart("$uploads");
        Scanner uploadsScanner = new Scanner(uploadsPart.getInputStream(),"UTF-8");
        StringBuilder uploadsJSONStringBuilder = new StringBuilder();
        while (uploadsScanner.hasNextLine())
            uploadsJSONStringBuilder.append(uploadsScanner.nextLine());

        Part argsPart = req.getPart("$args");
        Scanner argsScanner = new Scanner(argsPart.getInputStream(),"UTF-8");
        StringBuilder argsJSONStringBuilder = new StringBuilder();
        while (argsScanner.hasNextLine())
            argsJSONStringBuilder.append(argsScanner.nextLine());

        Gson gson = new Gson();
        Map<String,Object> uploadsMap = gson.fromJson(uploadsJSONStringBuilder.toString(),Map.class);
        Map<String,Object> argsMaps = gson.fromJson(argsJSONStringBuilder.toString(),Map.class);
        MethodParam methodParams[] = frontierMethod.getParams();

        for(MethodParam methodParam : methodParams)
            paramsMap.put(methodParam.getName(),getParamValue(frontier,frontierMethod,methodParam,uploadsMap,argsMaps,req));


    }catch (IOException | ServletException ex){

        throw new FrontierCallException(frontier,frontierMethod.getName(),"Failed to read parameters of frontier call with files attached",ex);

    }

}
 
Example 6
Project: spr   File: UploadServlet.java   View Source Code Vote up 5 votes
/**
 * Gestiona la subida de archivos
 */        
@Override
protected void doPost(HttpServletRequest request,
        HttpServletResponse response) throws ServletException, IOException {        		
    //obtiene el path relativo de subida de archivos de la aplicación
    String savePath = getServletContext().getInitParameter("file-upload"); 
     
    // crea la carpeta donde se guardaran los archivos si no existe
    File fileSaveDir = new File(savePath);
    if (!fileSaveDir.exists()) {
        fileSaveDir.mkdir();
    }
    
    //Obtiene el archivo desde la petición
    Part file = request.getPart("documento");
    String fileName = getFilename(file);
    
    
    //extrae la extension y el nombre de archivo por separado
    int dot = fileName.lastIndexOf(".");
    String fileNameExt = fileName.substring(dot);
    fileName = fileName.substring(0, dot);            
    
    //remplaza cualquier caracter del tipo espacio, puntos y otros por guión bajo.
    fileName = fileName.replaceAll("\\W","_");                        
    
    Date fecha = new Date();
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss_SSS");	
    String fechaStr = (String)sdf.format((fecha));
    
    file.write(savePath + File.separator + fechaStr +"_"+ fileName + fileNameExt);

    response.setContentType("text/plain");
	response.setCharacterEncoding("UTF-8");        
	
	if(fileName != null) response.getWriter().write(fechaStr +"_"+ fileName + fileNameExt);
	else
		response.getWriter().write("");
}
 
Example 7
Project: lams   File: RequestParamMethodArgumentResolver.java   View Source Code Vote up 5 votes
@Override
protected Object resolveName(String name, MethodParameter parameter, NativeWebRequest webRequest) throws Exception {
	Object arg;

	HttpServletRequest servletRequest = webRequest.getNativeRequest(HttpServletRequest.class);
	MultipartHttpServletRequest multipartRequest =
		WebUtils.getNativeRequest(servletRequest, MultipartHttpServletRequest.class);

	if (MultipartFile.class.equals(parameter.getParameterType())) {
		assertIsMultipartRequest(servletRequest);
		Assert.notNull(multipartRequest, "Expected MultipartHttpServletRequest: is a MultipartResolver configured?");
		arg = multipartRequest.getFile(name);
	}
	else if (isMultipartFileCollection(parameter)) {
		assertIsMultipartRequest(servletRequest);
		Assert.notNull(multipartRequest, "Expected MultipartHttpServletRequest: is a MultipartResolver configured?");
		arg = multipartRequest.getFiles(name);
	}
	else if(isMultipartFileArray(parameter)) {
		assertIsMultipartRequest(servletRequest);
		Assert.notNull(multipartRequest, "Expected MultipartHttpServletRequest: is a MultipartResolver configured?");
		arg = multipartRequest.getFiles(name).toArray(new MultipartFile[0]);
	}
	else if ("javax.servlet.http.Part".equals(parameter.getParameterType().getName())) {
		assertIsMultipartRequest(servletRequest);
		arg = servletRequest.getPart(name);
	}
	else if (isPartCollection(parameter)) {
		assertIsMultipartRequest(servletRequest);
		arg = new ArrayList<Object>(servletRequest.getParts());
	}
	else if (isPartArray(parameter)) {
		assertIsMultipartRequest(servletRequest);
		arg = RequestPartResolver.resolvePart(servletRequest);
	}
	else {
		arg = null;
		if (multipartRequest != null) {
			List<MultipartFile> files = multipartRequest.getFiles(name);
			if (!files.isEmpty()) {
				arg = (files.size() == 1 ? files.get(0) : files);
			}
		}
		if (arg == null) {
			String[] paramValues = webRequest.getParameterValues(name);
			if (paramValues != null) {
				arg = paramValues.length == 1 ? paramValues[0] : paramValues;
			}
		}
	}

	return arg;
}
 
Example 8
Project: tcp   File: UploadServlet.java   View Source Code Vote up 5 votes
/**
 * Gestiona la subida de archivos
 */        
@Override
protected void doPost(HttpServletRequest request,
        HttpServletResponse response) throws ServletException, IOException {        		
    //obtiene el path relativo de subida de archivos de la aplicación
    String savePath = getServletContext().getInitParameter("file-upload"); 
     
    // crea la carpeta donde se guardaran los archivos si no existe
    File fileSaveDir = new File(savePath);
    if (!fileSaveDir.exists()) {
        fileSaveDir.mkdir();
    }
    
    //Obtiene el archivo desde la petición
    Part file = request.getPart("documentoEvidencia");
    String fileName = getFilename(file);
    
    
    //extrae la extension y el nombre de archivo por separado
    int dot = fileName.lastIndexOf(".");
    String fileNameExt = fileName.substring(dot);
    fileName = fileName.substring(0, dot);            
    
    //remplaza cualquier caracter del tipo espacio, puntos y otros por guión bajo.
    fileName = fileName.replaceAll("\\W","_");                        
    
    Date fecha = new Date();
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss_SSS");	
    String fechaStr = (String)sdf.format((fecha));
    
    file.write(savePath + File.separator + fechaStr +"_"+ fileName + fileNameExt);

    response.setContentType("text/plain");
	response.setCharacterEncoding("UTF-8");        
	
	if(fileName != null) response.getWriter().write(savePath + File.separator + fechaStr +"_"+ fileName + fileNameExt);
	else
		response.getWriter().write("");
}
 
Example 9
Project: GroupControlDroidClient   File: UploadServlet.java   View Source Code Vote up 5 votes
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
	// InputStream in = req.getInputStream();
	PrintWriter out = resp.getWriter();
	String operationStr = null;

	req.setCharacterEncoding("UTF-8");
	Part part = req.getPart("file");
	OperationBean operationBean = new OperationBean();
	if (part != null) {
		String fileName = part.getSubmittedFileName();
		if (fileName.length() > 0) {
			part.write(fileName);

			File file = new File(System.getProperty("user.dir") + JettyConfig.UPLOAD_TMP_PATH);
			if (file.exists()) {
				logger.info("上传成功");
				operationBean.setCode(200);
				operationBean.setMsg(fileName);
			} else {
				logger.info("上传失败");
				operationBean.setCode(400);
				operationBean.setMsg("");
			}
		}else {
			SystemWSSender.error("请先浏览到您要安装的app安装包。");
		}
	}
	operationStr = JsonUtil.beanToJson(operationBean);
	logger.info(operationStr);
	out.println(operationStr);
	out.flush();
	out.close();
}
 
Example 10
Project: incubator-servicecomb-java-chassis   File: FormProcessorCreator.java   View Source Code Vote up 4 votes
@Override
public Object getValue(HttpServletRequest request) throws Exception {
  return request.getPart(paramPath);
}
 
Example 11
Project: tomcat7   File: HTMLManagerServlet.java   View Source Code Vote up 4 votes
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 12
Project: apache-tomcat-7.0.73-with-comment   File: HTMLManagerServlet.java   View Source Code Vote up 4 votes
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 13
Project: lazycat   File: HTMLManagerServlet.java   View Source Code Vote up 4 votes
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;
}