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

The following examples show how to use javax.servlet.http.HttpServletRequest#getParts() . 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: StandardMultipartHttpServletRequest.java    From spring-analysis-note with MIT License 10 votes vote down vote up
private void parseRequest(HttpServletRequest request) {
	try {
		Collection<Part> parts = request.getParts();
		this.multipartParameterNames = new LinkedHashSet<>(parts.size());
		MultiValueMap<String, MultipartFile> files = new LinkedMultiValueMap<>(parts.size());
		for (Part part : parts) {
			String headerValue = part.getHeader(HttpHeaders.CONTENT_DISPOSITION);
			ContentDisposition disposition = ContentDisposition.parse(headerValue);
			String filename = disposition.getFilename();
			if (filename != null) {
				if (filename.startsWith("=?") && filename.endsWith("?=")) {
					filename = MimeDelegate.decode(filename);
				}
				files.add(part.getName(), new StandardMultipartFile(part, filename));
			}
			else {
				this.multipartParameterNames.add(part.getName());
			}
		}
		setMultipartFiles(files);
	}
	catch (Throwable ex) {
		handleParseFailure(ex);
	}
}
 
Example 2
Source File: FileUploadServlet.java    From journaldev with MIT License 6 votes vote down vote up
protected void doPost(HttpServletRequest request,
        HttpServletResponse response) throws ServletException, IOException {
    // gets absolute path of the web application
    String applicationPath = request.getServletContext().getRealPath("");
    // constructs path of the directory to save uploaded file
    String uploadFilePath = applicationPath + File.separator + UPLOAD_DIR;
     
    // creates the save directory if it does not exists
    File fileSaveDir = new File(uploadFilePath);
    if (!fileSaveDir.exists()) {
        fileSaveDir.mkdirs();
    }
    System.out.println("Upload File Directory="+fileSaveDir.getAbsolutePath());
    
    String fileName = null;
    //Get all the parts from request and write it to the file on server
    for (Part part : request.getParts()) {
        fileName = getFileName(part);
        part.write(uploadFilePath + File.separator + fileName);
    }
 
    request.setAttribute("message", fileName + " File uploaded successfully!");
    getServletContext().getRequestDispatcher("/response.jsp").forward(
            request, response);
}
 
Example 3
Source File: MockMultiPartServlet.java    From requests with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    request.setAttribute(Request.__MULTIPART_CONFIG_ELEMENT, MULTI_PART_CONFIG);

    Collection<Part> parts = request.getParts();

    response.setContentType("text/plain");
    response.setCharacterEncoding("UTF-8");
    response.setStatus(HttpServletResponse.SC_OK);
    OutputStream out = response.getOutputStream();
    for (Part part : parts) {
        out.write(part.getName().getBytes(StandardCharsets.UTF_8));
        out.write('\n');
        if (part.getContentType() != null) {
            out.write(part.getContentType().getBytes(StandardCharsets.UTF_8));
            out.write('\n');
        }
        try (InputStream in = part.getInputStream()) {
            InputStreams.transferTo(in, out);
        }
        out.write('\n');
    }
}
 
Example 4
Source File: UploadServlet.java    From psychoPATH with GNU General Public License v3.0 6 votes vote down vote up
/**
    * handles file upload
    */
   protected void doPost(HttpServletRequest request,
           HttpServletResponse response) throws ServletException, IOException {
       // gets absolute path of the web application
       String appPath = request.getServletContext().getRealPath("");
       // constructs path of the directory to save uploaded file
// appPath + File.separator
       String savePath =  SAVE_DIR;
        
       // creates the save directory if it does not exists
       File fileSaveDir = new File(savePath);
       if (!fileSaveDir.exists()) {
           fileSaveDir.mkdir(); 
       }
       String full_name=SAVE_DIR;
       for (Part part : request.getParts()) {
           String fileName = extractFileName(part);
    fileName=fileName.replaceAll("\\.\\.","");
           part.write(savePath + File.separator + fileName);
    full_name=savePath + File.separator + fileName;
       }

       request.setAttribute("message", "Upload has been done successfully!");
       getServletContext().getRequestDispatcher("/message.jsp").forward(
               request, response);
   }
 
Example 5
Source File: UploadServlet.java    From psychoPATH with GNU General Public License v3.0 6 votes vote down vote up
/**
    * handles file upload
    */
   protected void doPost(HttpServletRequest request,
           HttpServletResponse response) throws ServletException, IOException {
       // gets absolute path of the web application
       String appPath = request.getServletContext().getRealPath("");
       // constructs path of the directory to save uploaded file
// appPath + File.separator
       String savePath =  SAVE_DIR;
        
       // creates the save directory if it does not exists
       File fileSaveDir = new File(savePath);
       if (!fileSaveDir.exists()) {
           fileSaveDir.mkdir(); 
       }
       String full_name=SAVE_DIR;
       for (Part part : request.getParts()) {
           String fileName = extractFileName(part);
           part.write(savePath + File.separator + fileName);
    full_name=savePath + File.separator + fileName;
       }

       request.setAttribute("message", "Upload has been done successfully!");
       getServletContext().getRequestDispatcher("/message.jsp").forward(
               request, response);
   }
 
Example 6
Source File: MultipartServlet.java    From tutorials with MIT License 6 votes vote down vote up
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String uploadPath = getServletContext().getRealPath("") + File.separator + UPLOAD_DIRECTORY;
        File uploadDir = new File(uploadPath);
        if (!uploadDir.exists())
            uploadDir.mkdir();

        try {
            String fileName = "";
            for (Part part : request.getParts()) {
                fileName = getFileName(part);
                part.write(uploadPath + File.separator + fileName);
            }
            request.setAttribute("message", "File " + fileName + " has uploaded successfully!");
        } catch (FileNotFoundException fne) {
            request.setAttribute("message", "There was an error: " + fne.getMessage());
        }
        getServletContext().getRequestDispatcher("/result.jsp").forward(request, response);
    }
 
Example 7
Source File: RequestMonitor.java    From curl with The Unlicense 5 votes vote down vote up
@RequestMapping (value = "/public/form", produces = MediaType.TEXT_PLAIN_VALUE, method = RequestMethod.POST)
@ResponseStatus (code = HttpStatus.OK)
@ResponseBody
public String form (final HttpServletRequest request) throws ServletException, IOException {
    final Collection<Part> parts = request.getParts ();
    RequestMonitor.LOGGER.info (parts.toString ());
    return this.logRequest (request, "");
}
 
Example 8
Source File: ScriptSourceUploadServlet.java    From BotLibre with Eclipse Public License 1.0 5 votes vote down vote up
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	SessionProxyBean proxy = (SessionProxyBean)request.getSession().getAttribute("proxy");
	LoginBean loginBean = getLoginBean(request, response);
	if (loginBean == null) {
		httpSessionTimeout(request, response);
		return;
	}
	ScriptBean bean = loginBean.getBean(ScriptBean.class);
	try {
		String postToken = (String)request.getParameter("postToken");
		loginBean.verifyPostToken(postToken);
		String instance = (String)request.getParameter("instance");
		if (instance != null) {
			if (bean.getInstance() == null || !String.valueOf(bean.getInstanceId()).equals(instance)) {
				bean.validateInstance(instance);
			}
		}
		String version = (String)request.getParameter("version");
		String versionName = (String)request.getParameter("versionName");
		String encoding = (String)request.getParameter("import-encoding");
		Collection<Part> files = request.getParts();
		int count = 0;
		for (Part filePart : files) {
			if (!filePart.getName().equals("file")) {
				continue;
			}
			if (filePart != null) {
				InputStream stream = filePart.getInputStream();
				bean.updateScriptSource(stream, encoding, "on".equals(version), versionName);
				count++;
			}
		}
		if (count == 0) {
			throw new BotException("Please select the source file to upload");
		}
	} catch (Throwable failed) {
		loginBean.error(failed);
	}
	response.sendRedirect("script?source=true&id=" + bean.getInstanceId() + proxy.proxyString());
}
 
Example 9
Source File: UploadCustomerDocumentsServlet.java    From tutorials with MIT License 5 votes vote down vote up
protected void doPost(
 HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    for (Part part : request.getParts()) {
        part.write("myFile");
    }
  
    PrintWriter writer = response.getWriter();
    writer.println("<html>File uploaded successfully!</html>");
    writer.flush();
}
 
Example 10
Source File: TestServerMultiPartContentEcho.java    From webtau with Apache License 2.0 5 votes vote down vote up
@Override
public byte[] responseBody(HttpServletRequest request) throws IOException, ServletException {
    Collection<Part> parts = request.getParts();

    Part part = new ArrayList<>(parts).get(partIdx);
    return IOUtils.toByteArray(part.getInputStream());
}
 
Example 11
Source File: ImportTranslationsServlet.java    From BotLibre with Eclipse Public License 1.0 5 votes vote down vote up
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	LoginBean loginBean = getLoginBean(request, response);
	if (loginBean == null) {
		httpSessionTimeout(request, response);
		return;
	}
	try {
		String postToken = (String)request.getParameter("postToken");
		loginBean.verifyPostToken(postToken);
		Collection<Part> files = request.getParts();
		int count = 0;
		for (Part filePart : files) {
			if (!filePart.getName().equals("file")) {
				continue;
			}
			if (filePart != null) {
				InputStream stream = filePart.getInputStream();
				loginBean.importTranslations(stream);
				count++;
			}
		}
		if (count == 0) {
			throw new BotException("Please select the XML file");
		}
	} catch (Throwable failed) {
		loginBean.error(failed);
	}
	response.sendRedirect("translation.jsp");		
}
 
Example 12
Source File: RequestPartMethodArgumentResolver.java    From spring4-understanding with Apache License 2.0 4 votes vote down vote up
public static Object resolvePart(HttpServletRequest servletRequest) throws Exception {
	Collection<Part> parts = servletRequest.getParts();
	return parts.toArray(new Part[parts.size()]);
}
 
Example 13
Source File: RequestPartMethodArgumentResolver.java    From spring4-understanding with Apache License 2.0 4 votes vote down vote up
@Override
@UsesJava8
public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
		NativeWebRequest request, WebDataBinderFactory binderFactory) throws Exception {

	HttpServletRequest servletRequest = request.getNativeRequest(HttpServletRequest.class);
	assertIsMultipartRequest(servletRequest);

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

	Class<?> paramType = parameter.getParameterType();
	boolean optional = paramType.getName().equals("java.util.Optional");
	if (optional) {
		parameter.increaseNestingLevel();
		paramType = parameter.getNestedParameterType();
	}

	String partName = getPartName(parameter);
	Object arg;

	if (MultipartFile.class == paramType) {
		Assert.notNull(multipartRequest, "Expected MultipartHttpServletRequest: is a MultipartResolver configured?");
		arg = multipartRequest.getFile(partName);
	}
	else if (isMultipartFileCollection(parameter)) {
		Assert.notNull(multipartRequest, "Expected MultipartHttpServletRequest: is a MultipartResolver configured?");
		arg = multipartRequest.getFiles(partName);
	}
	else if (isMultipartFileArray(parameter)) {
		Assert.notNull(multipartRequest, "Expected MultipartHttpServletRequest: is a MultipartResolver configured?");
		List<MultipartFile> files = multipartRequest.getFiles(partName);
		arg = files.toArray(new MultipartFile[files.size()]);
	}
	else if ("javax.servlet.http.Part".equals(paramType.getName())) {
		assertIsMultipartRequest(servletRequest);
		arg = servletRequest.getPart(partName);
	}
	else if (isPartCollection(parameter)) {
		assertIsMultipartRequest(servletRequest);
		arg = new ArrayList<Object>(servletRequest.getParts());
	}
	else if (isPartArray(parameter)) {
		assertIsMultipartRequest(servletRequest);
		arg = RequestPartResolver.resolvePart(servletRequest);
	}
	else {
		try {
			HttpInputMessage inputMessage = new RequestPartServletServerHttpRequest(servletRequest, partName);
			arg = readWithMessageConverters(inputMessage, parameter, parameter.getNestedGenericParameterType());
			WebDataBinder binder = binderFactory.createBinder(request, arg, partName);
			if (arg != null) {
				validateIfApplicable(binder, parameter);
				if (binder.getBindingResult().hasErrors() && isBindExceptionRequired(binder, parameter)) {
					throw new MethodArgumentNotValidException(parameter, binder.getBindingResult());
				}
			}
			mavContainer.addAttribute(BindingResult.MODEL_KEY_PREFIX + partName, binder.getBindingResult());
		}
		catch (MissingServletRequestPartException ex) {
			// handled below
			arg = null;
		}
	}

	RequestPart requestPart = parameter.getParameterAnnotation(RequestPart.class);
	boolean isRequired = ((requestPart == null || requestPart.required()) && !optional);

	if (arg == null && isRequired) {
		throw new MissingServletRequestPartException(partName);
	}
	if (optional) {
		arg = Optional.ofNullable(arg);
	}

	return arg;
}
 
Example 14
Source File: TestServerMultiPartMetaEcho.java    From webtau with Apache License 2.0 4 votes vote down vote up
@Override
public byte[] responseBody(HttpServletRequest request) throws IOException, ServletException {
    Collection<Part> parts = request.getParts();
    return JsonUtils.serialize(parts.stream().map(this::partToMap).collect(toList())).getBytes();
}
 
Example 15
Source File: DocumentTemplateBinaryResource.java    From eplmp with Eclipse Public License 1.0 4 votes vote down vote up
@POST
@ApiOperation(value = "Upload document template file",
        response = Response.class)
@ApiImplicitParams({
        @ApiImplicitParam(name = "upload", paramType = "formData", dataType = "file", required = true)
})
@ApiResponses(value = {
        @ApiResponse(code = 204, message = "Upload success"),
        @ApiResponse(code = 401, message = "Unauthorized"),
        @ApiResponse(code = 403, message = "Forbidden"),
        @ApiResponse(code = 500, message = "Internal server error")
})
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response uploadDocumentTemplateFiles(
        @Context HttpServletRequest request,
        @ApiParam(required = true, value = "Workspace id") @PathParam("workspaceId") final String workspaceId,
        @ApiParam(required = true, value = "Template id") @PathParam("templateId") final String templateId)
        throws EntityNotFoundException, EntityAlreadyExistsException, UserNotActiveException, AccessRightException,
        NotAllowedException, CreationException, WorkspaceNotEnabledException {

    try {
        BinaryResource binaryResource;
        String fileName = null;
        long length;
        DocumentMasterTemplateKey templatePK = new DocumentMasterTemplateKey(workspaceId, templateId);
        Collection<Part> formParts = request.getParts();

        for (Part formPart : formParts) {
            fileName = Normalizer.normalize(formPart.getSubmittedFileName(), Normalizer.Form.NFC);
            // Init the binary resource with a null length
            binaryResource = documentService.saveFileInTemplate(templatePK, fileName, 0);
            OutputStream outputStream = storageManager.getBinaryResourceOutputStream(binaryResource);
            length = BinaryResourceUpload.uploadBinary(outputStream, formPart);
            documentService.saveFileInTemplate(templatePK, fileName, length);
        }

        if (fileName == null){
            return Response.status(Response.Status.BAD_REQUEST).build();
        }

        if (formParts.size() == 1) {
            return BinaryResourceUpload.tryToRespondCreated(request.getRequestURI() + URLEncoder.encode(fileName, "UTF-8"));
        }

        return Response.noContent().build();

    } catch (IOException | ServletException | StorageException e) {
        return BinaryResourceUpload.uploadError(e);
    }
}
 
Example 16
Source File: FileUploaderEndpoint.java    From tool.accelerate.core with Apache License 2.0 4 votes vote down vote up
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String tech = request.getParameter(PARAMETER_TECH);
    String workspaceId = request.getParameter(PARAMETER_WORKSPACE);    //specify the unique workspace directory to upload the file(s) to.    
    Collection<Part> filePartCollection = request.getParts();
    
    String serverHostPort = request.getRequestURL().toString().replace(request.getRequestURI(), "");
    int schemeLength = request.getScheme().toString().length();
    String internalHostPort = "http" + serverHostPort.substring(schemeLength);
    log.log(Level.FINER, "serverHostPort : " + serverHostPort);
    final ServiceConnector serviceConnector = new ServiceConnector(serverHostPort, internalHostPort);
    HashMap<Part, String> fileNames = new HashMap<Part, String>();
    if(!isValidRequest(request, response, tech, workspaceId, filePartCollection, serviceConnector, fileNames)){
        return;
    }

    Service techService = serviceConnector.getServiceObjectFromId(tech);
    String techDirPath = StarterUtil.getWorkspaceDir(workspaceId) + "/" + techService.getId();
    File techDir = new File(techDirPath);
    if(techDir.exists() && techDir.isDirectory() && "true".equalsIgnoreCase(request.getParameter(PARAMETER_CLEANUP))){
        FileUtils.cleanDirectory(techDir);
        log.log(Level.FINER, "Cleaned up tech workspace directory : " + techDirPath);
    }

    for (Part filePart : filePartCollection){
        if(!techDir.exists()){
            FileUtils.forceMkdir(techDir);
            log.log(Level.FINER, "Created tech directory :" + techDirPath);
        }
        
        String filePath = techDirPath + "/" + fileNames.get(filePart);
        log.log(Level.FINER, "File path : " + filePath);
        File uploadedFile = new File(filePath);

        Files.copy(filePart.getInputStream(), uploadedFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
        log.log(Level.FINE, "Copied file to " + filePath);    
    }

    if("true".equalsIgnoreCase(request.getParameter(PARAMETER_PROCESS))){
        // Process uploaded file(s)
        String processResult = serviceConnector.processUploadedFiles(techService, techDirPath);
        if(!processResult.equalsIgnoreCase("success")){
            log.log(Level.INFO, "Error processing the files uploaded to " + techDirPath + " : Result=" + processResult);
            response.sendError(500, processResult);
            return;
        }
        log.log(Level.FINE, "Processed the files uploaded to " + techDirPath);    
    }

    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    out.println("success");
    out.close();
}
 
Example 17
Source File: ImageUpload.java    From OnlineShoppingSystem with MIT License 4 votes vote down vote up
/**
 * 上传多个图片
 * 
 * @param request
 * @return
 */
public boolean uploadImages(HttpServletRequest request) {
    boolean success = false;
    int count = -1;
    ArrayList<Part> images;
    try {
        images = (ArrayList<Part>) request.getParts();
        count = images.size();
        for (Part image : images) {
            System.out.println(image.getName());

            InputStream imageInputStream = null;

            if (image != null && image.getSize() != 0) {
                try {
                    imageInputStream = image.getInputStream();

                    if (imageInputStream != null) {
                        String imagedir = request.getServletContext()
                                .getInitParameter("imagedir")
                                + File.separator
                                + "avatars"
                                + File.separator;

                        // 图片名格式:20161123204206613375.jpg。
                        // 代表 2016-11-23 20:42:06.613 + 3 位 0 - 9 间随机数字
                        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmssSSS");
                        StringBuilder imageName = new StringBuilder(
                                dateFormat.format(new Date()));
                        Random random = new Random();
                        for (int i = 0; i < 3; ++i) {
                            imageName.append(random.nextInt(10));
                        }
                        imageName.append(".jpg");

                        String targetFile = imagedir + imageName;
                        System.out.println(targetFile);
                        try {
                            FileUtils.copyInputStreamToFile(imageInputStream,
                                    new File(targetFile));

                            count--;
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                } catch (IOException e1) {
                    e1.printStackTrace();
                } finally {
                    imageInputStream.close();
                }
            }
        }
    } catch (IOException | ServletException e3) {
        e3.printStackTrace();
    }
    if (count == 0) {
        success = true;
    } else {
        success = false;
    }

    return success;
}
 
Example 18
Source File: PartBinaryResource.java    From eplmp with Eclipse Public License 1.0 4 votes vote down vote up
@POST
@ApiOperation(value = "Upload attached file",
        response = Response.class)
@ApiImplicitParams({
        @ApiImplicitParam(name = "upload", paramType = "formData", dataType = "file", required = true)
})
@ApiResponses(value = {
        @ApiResponse(code = 204, message = "Upload success"),
        @ApiResponse(code = 401, message = "Unauthorized"),
        @ApiResponse(code = 403, message = "Forbidden"),
        @ApiResponse(code = 500, message = "Internal server error")
})
@Path("/{iteration}/" + PartIteration.ATTACHED_FILES_SUBTYPE)
@Consumes(MediaType.MULTIPART_FORM_DATA)
@RolesAllowed({UserGroupMapping.REGULAR_USER_ROLE_ID})
public Response uploadAttachedFiles(
        @Context HttpServletRequest request,
        @ApiParam(required = true, value = "Workspace id") @PathParam("workspaceId") final String workspaceId,
        @ApiParam(required = true, value = "Part number") @PathParam("partNumber") final String partNumber,
        @ApiParam(required = true, value = "Part version") @PathParam("version") final String version,
        @ApiParam(required = true, value = "Part iteration") @PathParam("iteration") final int iteration)
        throws EntityNotFoundException, EntityAlreadyExistsException, UserNotActiveException, AccessRightException,
        NotAllowedException, CreationException, WorkspaceNotEnabledException {

    try {

        PartIterationKey partPK = new PartIterationKey(workspaceId, partNumber, version, iteration);
        Collection<Part> formParts = request.getParts();

        String fileName = null;

        for (Part formPart : formParts) {
            fileName = Normalizer.normalize(formPart.getSubmittedFileName(), Normalizer.Form.NFC);
            BinaryResource binaryResource = productService.saveFileInPartIteration(partPK, fileName, PartIteration.ATTACHED_FILES_SUBTYPE, 0);
            OutputStream outputStream = storageManager.getBinaryResourceOutputStream(binaryResource);
            long length = BinaryResourceUpload.uploadBinary(outputStream, formPart);
            productService.saveFileInPartIteration(partPK, fileName, PartIteration.ATTACHED_FILES_SUBTYPE, length);
        }

        if (formParts.size() == 1) {
            return BinaryResourceUpload.tryToRespondCreated(request.getRequestURI() + URLEncoder.encode(fileName, UTF8_ENCODING));
        }

        return Response.noContent().build();

    } catch (IOException | ServletException | StorageException e) {
        return BinaryResourceUpload.uploadError(e);
    }
}
 
Example 19
Source File: DocumentBinaryResource.java    From eplmp with Eclipse Public License 1.0 4 votes vote down vote up
@POST
@ApiOperation(value = "Upload document file",
        response = Response.class,
        authorizations = {@Authorization(value = "authorization")})
@ApiResponses(value = {
        @ApiResponse(code = 204, message = "Upload success"),
        @ApiResponse(code = 401, message = "Unauthorized"),
        @ApiResponse(code = 403, message = "Forbidden"),
        @ApiResponse(code = 500, message = "Internal server error")
})
@ApiImplicitParams({
        @ApiImplicitParam(name = "upload", paramType = "formData", dataType = "file", required = true)
})
@Path("/{iteration}")
@Consumes(MediaType.MULTIPART_FORM_DATA)
@RolesAllowed({UserGroupMapping.REGULAR_USER_ROLE_ID})
public Response uploadDocumentFiles(
        @Context HttpServletRequest request,
        @ApiParam(required = true, value = "Workspace id") @PathParam("workspaceId") final String workspaceId,
        @ApiParam(required = true, value = "Document master id") @PathParam("documentId") final String documentId,
        @ApiParam(required = true, value = "Workspace version") @PathParam("version") final String version,
        @ApiParam(required = true, value = "Document iteration") @PathParam("iteration") final int iteration)
        throws EntityNotFoundException, EntityAlreadyExistsException, UserNotActiveException, AccessRightException,
        NotAllowedException, CreationException, WorkspaceNotEnabledException {

    try {
        String fileName = null;
        DocumentIterationKey docPK = new DocumentIterationKey(workspaceId, documentId, version, iteration);
        Collection<Part> formParts = request.getParts();

        for (Part formPart : formParts) {
            fileName = uploadAFile(formPart, docPK);
        }

        if (fileName == null) {
            return Response.status(Response.Status.BAD_REQUEST).build();
        }

        if (formParts.size() == 1) {
            return BinaryResourceUpload.tryToRespondCreated(request.getRequestURI() + URLEncoder.encode(fileName, "UTF-8"));
        }

        return Response.noContent().build();
    } catch (IOException | ServletException | StorageException e) {
        return BinaryResourceUpload.uploadError(e);
    }
}
 
Example 20
Source File: FileUploadServlet.java    From Tutorials with Apache License 2.0 4 votes vote down vote up
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
		throws ServletException, IOException {

	response.setContentType("text/html");
	response.setCharacterEncoding("UTF-8");

	// gets absolute path of the web application
	String applicationPath = request.getServletContext().getRealPath("");
	// constructs path of the directory to save uploaded file
	String uploadFilePath = applicationPath + File.separator + UPLOAD_DIR;

	// creates upload folder if it does not exists
	File uploadFolder = new File(uploadFilePath);
	if (!uploadFolder.exists()) {
		uploadFolder.mkdirs();
	}

	PrintWriter writer = response.getWriter();

	// write all files in upload folder
	for (Part part : request.getParts()) {
		if (part != null && part.getSize() > 0) {
			String fileName = part.getSubmittedFileName();
			String contentType = part.getContentType();
			
			// allows only JPEG files to be uploaded
			if (!contentType.equalsIgnoreCase("image/jpeg")) {
				continue;
			}
			
			part.write(uploadFilePath + File.separator + fileName);
			
			writer.append("File successfully uploaded to " 
					+ uploadFolder.getAbsolutePath() 
					+ File.separator
					+ fileName
					+ "<br>\r\n");
		}
	}

}