javax.servlet.http.Part Java Examples

The following examples show how to use javax.servlet.http.Part. 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 lams with GNU General Public License v2.0 7 votes vote down vote up
private void parseRequest(HttpServletRequest request) {
	try {
		Collection<Part> parts = request.getParts();
		this.multipartParameterNames = new LinkedHashSet<String>(parts.size());
		MultiValueMap<String, MultipartFile> files = new LinkedMultiValueMap<String, MultipartFile>(parts.size());
		for (Part part : parts) {
			String disposition = part.getHeader(CONTENT_DISPOSITION);
			String filename = extractFilename(disposition);
			if (filename == null) {
				filename = extractFilenameWithCharset(disposition);
			}
			if (filename != null) {
				files.add(part.getName(), new StandardMultipartFile(part, filename));
			}
			else {
				this.multipartParameterNames.add(part.getName());
			}
		}
		setMultipartFiles(files);
	}
	catch (Throwable ex) {
		throw new MultipartException("Could not parse multipart servlet request", ex);
	}
}
 
Example #2
Source File: RequestParamMethodArgumentResolverTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void resolvePartList() throws Exception {
	MockHttpServletRequest request = new MockHttpServletRequest();
	request.setMethod("POST");
	request.setContentType("multipart/form-data");
	MockPart expected1 = new MockPart("pfilelist", "Hello World 1".getBytes());
	MockPart expected2 = new MockPart("pfilelist", "Hello World 2".getBytes());
	request.addPart(expected1);
	request.addPart(expected2);
	request.addPart(new MockPart("other", "Hello World 3".getBytes()));
	webRequest = new ServletWebRequest(request);

	MethodParameter param = this.testMethod.annotPresent(RequestParam.class).arg(List.class, Part.class);
	Object result = resolver.resolveArgument(param, null, webRequest, null);

	assertTrue(result instanceof List);
	assertEquals(Arrays.asList(expected1, expected2), result);
}
 
Example #3
Source File: StandardMultipartHttpServletRequest.java    From java-technology-stack with MIT License 6 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 #4
Source File: RequestParamMapMethodArgumentResolverTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void resolveMapOfPart() throws Exception {
	MockHttpServletRequest request = new MockHttpServletRequest();
	request.setContentType("multipart/form-data");
	Part expected1 = new MockPart("mfile", "Hello World".getBytes());
	Part expected2 = new MockPart("other", "Hello World 3".getBytes());
	request.addPart(expected1);
	request.addPart(expected2);
	webRequest = new ServletWebRequest(request);

	MethodParameter param = this.testMethod.annot(requestParam().noName()).arg(Map.class, String.class, Part.class);
	Object result = resolver.resolveArgument(param, null, webRequest, null);

	assertTrue(result instanceof Map);
	Map<String, Part> resultMap = (Map<String, Part>) result;
	assertEquals(2, resultMap.size());
	assertEquals(expected1, resultMap.get("mfile"));
	assertEquals(expected2, resultMap.get("other"));
}
 
Example #5
Source File: RequestPartMethodArgumentResolverTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void resolvePartArrayArgument() throws Exception {
	MockPart part1 = new MockPart("requestPart1", "Hello World 1".getBytes());
	MockPart part2 = new MockPart("requestPart2", "Hello World 2".getBytes());
	MockHttpServletRequest request = new MockHttpServletRequest();
	request.setMethod("POST");
	request.setContentType("multipart/form-data");
	request.addPart(part1);
	request.addPart(part2);
	webRequest = new ServletWebRequest(request);

	Object result = resolver.resolveArgument(paramPartArray, null, webRequest, null);

	assertTrue(result instanceof Part[]);
	Part[] parts = (Part[]) result;
	assertThat(parts, Matchers.arrayWithSize(2));
	assertEquals(parts[0], part1);
	assertEquals(parts[1], part2);
}
 
Example #6
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 #7
Source File: RequestParamMethodArgumentResolverTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void resolvePartArray() throws Exception {
	MockHttpServletRequest request = new MockHttpServletRequest();
	MockPart expected1 = new MockPart("pfilearray", "Hello World 1".getBytes());
	MockPart expected2 = new MockPart("pfilearray", "Hello World 2".getBytes());
	request.setMethod("POST");
	request.setContentType("multipart/form-data");
	request.addPart(expected1);
	request.addPart(expected2);
	request.addPart(new MockPart("other", "Hello World 3".getBytes()));
	webRequest = new ServletWebRequest(request);

	MethodParameter param = this.testMethod.annotPresent(RequestParam.class).arg(Part[].class);
	Object result = resolver.resolveArgument(param, null, webRequest, null);

	assertTrue(result instanceof Part[]);
	Part[] parts = (Part[]) result;
	assertEquals(2, parts.length);
	assertEquals(parts[0], expected1);
	assertEquals(parts[1], expected2);
}
 
Example #8
Source File: UploadHelper.java    From HongsCORE with MIT License 6 votes vote down vote up
/**
 * 检查上传对象并写入目标目录
 * @param part
 * @param subn
 * @return
 * @throws Wrong
 */
public File upload(Part part, String subn) throws Wrong {
    if (part == null) {
        setResultName("", null);
        return  null;
    }

    /**
     * 从上传项中获取类型并提取扩展名
     */
    String type = part.getContentType( /**/ );
           type = getTypeByMime( type );
    String extn = part.getSubmittedFileName();
           extn = getExtnByName( extn );

    try {
        return upload(part.getInputStream(), type, extn, subn);
    }
    catch ( IOException ex) {
        throw new Wrong(ex, "fore.form.upload.failed");
    }
}
 
Example #9
Source File: TestVertxServerResponseToHttpServletResponse.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
@Test
public void sendPart_succ(@Mocked Part part, @Mocked InputStream inputStream)
    throws IOException, InterruptedException, ExecutionException {
  new Expectations() {
    {
      part.getInputStream();
      result = inputStream;
      inputStream.read((byte[]) any);
      result = -1;
    }
  };

  CompletableFuture<Void> future = response.sendPart(part);

  Assert.assertNull(future.get());
}
 
Example #10
Source File: MockHttpServletRequest.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Override
public Collection<Part> getParts() throws IOException, IllegalStateException, ServletException {
	List<Part> result = new LinkedList<Part>();
	for (List<Part> list : this.parts.values()) {
		result.addAll(list);
	}
	return result;
}
 
Example #11
Source File: DocumentBinaryResourceTest.java    From eplmp with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Test to upload several file to a document
 *
 * @throws Exception
 */
@Test
public void uploadSeveralFilesToDocumentsTemplates() throws Exception {

    //Given
    HttpServletRequestWrapper request = Mockito.mock(HttpServletRequestWrapper.class);
    Collection<Part> filesParts = new ArrayList<>();
    filesParts.add(new PartImpl(new File(ResourceUtil.getFilePath(ResourceUtil.SOURCE_FILE_STORAGE + ResourceUtil.FILENAME1))));
    filesParts.add(new PartImpl(new File(ResourceUtil.getFilePath(ResourceUtil.SOURCE_FILE_STORAGE) + ResourceUtil.FILENAME2)));
    filesParts.add(new PartImpl(new File(ResourceUtil.getFilePath(ResourceUtil.SOURCE_FILE_STORAGE + ResourceUtil.FILENAME3))));

    BinaryResource binaryResource1 = new BinaryResource(ResourceUtil.FILENAME1, ResourceUtil.DOCUMENT_SIZE, new Date());
    BinaryResource binaryResource2 = new BinaryResource(ResourceUtil.FILENAME2, ResourceUtil.DOCUMENT_SIZE, new Date());
    BinaryResource binaryResource3 = new BinaryResource(ResourceUtil.FILENAME3, ResourceUtil.DOCUMENT_SIZE, new Date());

    File uploadedFile1 = File.createTempFile(ResourceUtil.TARGET_FILE_STORAGE + "new_" + ResourceUtil.FILENAME1, ResourceUtil.TEMP_SUFFIX);
    File uploadedFile2 = File.createTempFile(ResourceUtil.TARGET_FILE_STORAGE + "new_" + ResourceUtil.FILENAME2, ResourceUtil.TEMP_SUFFIX);
    File uploadedFile3 = File.createTempFile(ResourceUtil.TARGET_FILE_STORAGE + "new_" + ResourceUtil.FILENAME3, ResourceUtil.TEMP_SUFFIX);

    OutputStream outputStream1 = new FileOutputStream(uploadedFile1);
    OutputStream outputStream2 = new FileOutputStream(uploadedFile2);
    OutputStream outputStream3 = new FileOutputStream(uploadedFile3);
    Mockito.when(request.getParts()).thenReturn(filesParts);
    Mockito.when(documentService.saveFileInDocument(Matchers.any(DocumentIterationKey.class), Matchers.anyString(), Matchers.anyInt())).thenReturn(binaryResource1, binaryResource1, binaryResource2, binaryResource2, binaryResource3, binaryResource3);
    Mockito.when(storageManager.getBinaryResourceOutputStream(Matchers.any(BinaryResource.class))).thenReturn(outputStream1, outputStream2, outputStream3);
    //When
    Response response = documentBinaryResource.uploadDocumentFiles(request, ResourceUtil.WORKSPACE_ID, ResourceUtil.DOCUMENT_ID, ResourceUtil.VERSION, ResourceUtil.ITERATION);

    //Then
    assertNotNull(response);
    assertEquals(Response.Status.NO_CONTENT, response.getStatusInfo());

    //delete temp files
    uploadedFile1.deleteOnExit();
    uploadedFile2.deleteOnExit();
    uploadedFile3.deleteOnExit();

}
 
Example #12
Source File: UploadJaxrsSchema.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
private static String getStrFromPart(Part file1) {
  try (InputStream is1 = file1.getInputStream()) {
    return IOUtils.toString(is1, "utf-8");
  } catch (IOException e) {
    e.printStackTrace();
  }
  return "";
}
 
Example #13
Source File: TestInspectorImpl.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
private void testDownloadHtmlById(String schemaId) throws IOException {
  Response response = inspector.getSchemaContentById(schemaId, SchemaFormat.HTML, true);

  Part part = response.getResult();
  Assert.assertEquals(schemaId + ".html", part.getSubmittedFileName());
  Assert.assertNull(response.getHeaders().getFirst(HttpHeaders.CONTENT_DISPOSITION));
  Assert.assertEquals(MediaType.TEXT_HTML, response.getHeaders().getFirst(HttpHeaders.CONTENT_TYPE));

  try (InputStream is = part.getInputStream()) {
    Assert.assertTrue(IOUtils.toString(is, StandardCharsets.UTF_8).endsWith("</html>"));
  }
}
 
Example #14
Source File: DocumentBinaryResourceTest.java    From eplmp with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Test to upload a file to a document with special characters
 *
 * @throws Exception
 */
@Test
public void uploadFileWithSpecialCharactersToDocumentTemplates() throws Exception {

    //Given
    HttpServletRequestWrapper request = Mockito.mock(HttpServletRequestWrapper.class);
    Collection<Part> filesParts = new ArrayList<>();
    filesParts.add(new PartImpl(new File(ResourceUtil.getFilePath(ResourceUtil.SOURCE_FILE_STORAGE) + ResourceUtil.FILENAME2)));

    BinaryResource binaryResource = new BinaryResource(Tools.unAccent(ResourceUtil.FILENAME2), ResourceUtil.DOCUMENT_SIZE, new Date());

    File uploadedFile1 = File.createTempFile(ResourceUtil.TARGET_FILE_STORAGE + "new_" + ResourceUtil.FILENAME2, ResourceUtil.TEMP_SUFFIX);


    OutputStream outputStream1 = new FileOutputStream(uploadedFile1);

    Mockito.when(request.getParts()).thenReturn(filesParts);
    Mockito.when(documentService.saveFileInDocument(Matchers.any(DocumentIterationKey.class), Matchers.anyString(), Matchers.anyInt())).thenReturn(binaryResource);
    Mockito.when(storageManager.getBinaryResourceOutputStream(Matchers.any(BinaryResource.class))).thenReturn(outputStream1);
    Mockito.when(request.getRequestURI()).thenReturn(ResourceUtil.WORKSPACE_ID + "/documents/" + ResourceUtil.DOCUMENT_ID + "/" + ResourceUtil.FILENAME2);


    //When
    Response response = documentBinaryResource.uploadDocumentFiles(request, ResourceUtil.WORKSPACE_ID, ResourceUtil.DOCUMENT_ID, ResourceUtil.VERSION, ResourceUtil.ITERATION);

    //Then
    assertNotNull(response);
    assertEquals(201, response.getStatus());
    assertEquals(Response.Status.CREATED, response.getStatusInfo());

    //delete tem file
    uploadedFile1.deleteOnExit();
}
 
Example #15
Source File: UploadJaxrsSchema.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
@Path("/uploadArray2")
@POST
@Produces(MediaType.TEXT_PLAIN)
public String uploadArray2(@FormParam("file1") Part[] file1, @FormParam("message") String message)
    throws IOException {
  StringBuilder stringBuilder = new StringBuilder();
  for (int i = 0; i < file1.length; i++) {
    stringBuilder.append(getStrFromPart(file1[i]));
  }
  return stringBuilder.append(message).toString();
}
 
Example #16
Source File: RequestParamMethodArgumentResolverTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void resolvePart() throws Exception {
	MockHttpServletRequest request = new MockHttpServletRequest();
	MockPart expected = new MockPart("pfile", "Hello World".getBytes());
	request.setMethod("POST");
	request.setContentType("multipart/form-data");
	request.addPart(expected);
	webRequest = new ServletWebRequest(request);

	MethodParameter param = this.testMethod.annotPresent(RequestParam.class).arg(Part.class);
	Object result = resolver.resolveArgument(param, null, webRequest, null);

	assertTrue(result instanceof Part);
	assertEquals("Invalid result", expected, result);
}
 
Example #17
Source File: ProductInstanceBinaryResource.java    From eplmp with Eclipse Public License 1.0 5 votes vote down vote up
private String uploadAFile(String workspaceId, Part formPart, ProductInstanceIterationKey pdtIterationKey)
        throws EntityNotFoundException, EntityAlreadyExistsException, AccessRightException, NotAllowedException, CreationException, UserNotActiveException, StorageException, IOException, WorkspaceNotEnabledException {

    String fileName = Normalizer.normalize(formPart.getSubmittedFileName(), Normalizer.Form.NFC);
    // Init the binary resource with a null length
    BinaryResource binaryResource = productInstanceManagerLocal.saveFileInProductInstance(workspaceId, pdtIterationKey, fileName, 0);
    OutputStream outputStream = storageManager.getBinaryResourceOutputStream(binaryResource);
    long length = BinaryResourceUpload.uploadBinary(outputStream, formPart);
    productInstanceManagerLocal.saveFileInProductInstance(workspaceId, pdtIterationKey, fileName, (int) length);
    return fileName;
}
 
Example #18
Source File: ValidFeignClientTests.java    From spring-cloud-openfeign with Apache License 2.0 5 votes vote down vote up
@RequestMapping(method = RequestMethod.POST, path = "/multipartFilenames",
		consumes = MediaType.MULTIPART_FORM_DATA_VALUE,
		produces = MediaType.TEXT_PLAIN_VALUE)
String multipartFilenames(HttpServletRequest request) throws Exception {
	return request.getParts().stream().map(Part::getSubmittedFileName)
			.collect(Collectors.joining(","));
}
 
Example #19
Source File: StandardMultipartHttpServletRequest.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Override
public String getMultipartContentType(String paramOrFileName) {
	try {
		Part part = getPart(paramOrFileName);
		return (part != null ? part.getContentType() : null);
	}
	catch (Exception ex) {
		throw new MultipartException("Could not access multipart servlet request", ex);
	}
}
 
Example #20
Source File: MockHttpServletRequest.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
public Collection<Part> getParts() throws IOException, ServletException {
	List<Part> result = new LinkedList<>();
	for (List<Part> list : this.parts.values()) {
		result.addAll(list);
	}
	return result;
}
 
Example #21
Source File: TestStandardHttpServletResponseEx.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
@Test
public void sendPart_failed(@Mocked Part part) throws Throwable {
  RuntimeException error = new RuntimeExceptionWithoutStackTrace();
  new Expectations() {
    {
      response.getOutputStream();
      result = error;
    }
  };

  expectedException.expect(Matchers.sameInstance(error));

  responseEx.sendPart(part).get();
}
 
Example #22
Source File: PostResource.java    From fenixedu-cms with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Atomic(mode = TxMode.WRITE)
public void createFileFromRequest(Post post, Part part) throws IOException {
    AdminPosts.ensureCanEditPost(post);
    GroupBasedFile groupBasedFile = new GroupBasedFile(part.getName(), part.getName(),
            part.getInputStream(), Group.logged());

    PostFile postFile = new PostFile(post, groupBasedFile, false, 0);
    post.addFiles(postFile);
}
 
Example #23
Source File: HttpRequestImpl.java    From tomee with Apache License 2.0 5 votes vote down vote up
@Override
public Collection<Part> getParts() throws IOException, ServletException {
    if (parts == null) { // assume it is not init
        parts = CommonsFileUploadPartFactory.read(this);
    }
    return parts;
}
 
Example #24
Source File: TestServerRestArgsFilter.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
@Test
public void asyncBeforeSendResponse_part(@Mocked RestOperationMeta restOperationMeta) {
  ResponsesMeta responsesMeta = new ResponsesMeta();
  responsesMeta.getResponseMap().put(202, RestObjectMapperFactory.getRestObjectMapper().constructType(Part.class));
  new Expectations(RestMetaUtils.class) {
    {
      responseEx.getAttribute(RestConst.INVOCATION_HANDLER_RESPONSE);
      result = response;
      response.getResult();
      result = part;
      response.getStatusCode();
      result = 202;
      invocation.findResponseType(202);
      result = TypeFactory.defaultInstance().constructType(Part.class);
    }
  };
  new MockUp<HttpServletResponseEx>(responseEx) {
    @Mock
    CompletableFuture<Void> sendPart(Part body) {
      invokedSendPart = true;
      return null;
    }
  };

  Assert.assertNull(filter.beforeSendResponseAsync(invocation, responseEx));
  Assert.assertTrue(invokedSendPart);
}
 
Example #25
Source File: DataServlet.java    From BLELocalization with 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 #26
Source File: MultipartControllerTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@RequestMapping(value = "/part", method = RequestMethod.POST)
public String processPart(@RequestParam Part part,
		@RequestPart Map<String, String> json, Model model) throws IOException {

	model.addAttribute("fileContent", part.getInputStream());
	model.addAttribute("jsonContent", json);

	return "redirect:/index";
}
 
Example #27
Source File: CodeFirstJaxrs.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
@Path("/upload2")
@POST
@Produces(MediaType.TEXT_PLAIN)
public String fileUpload2(@FormParam("file1") Part file1, @FormParam("message") String message) throws IOException {
  try (InputStream is1 = file1.getInputStream()) {
    String content1 = IOUtils.toString(is1, StandardCharsets.UTF_8);
    return String.format("%s:%s:%s:%s",
        file1.getSubmittedFileName(),
        file1.getContentType(),
        content1,
        message);
  }
}
 
Example #28
Source File: Ingest.java    From oryx with Apache License 2.0 5 votes vote down vote up
@POST
@Consumes(MediaType.MULTIPART_FORM_DATA)
public void post(@Context HttpServletRequest request) throws IOException, OryxServingException {
  checkNotReadOnly();
  for (Part item : parseMultipart(request)) {
    try (BufferedReader reader = maybeBuffer(maybeDecompress(item))) {
      doPost(reader);
    }
  }
}
 
Example #29
Source File: HttpServletRequestAdapter.java    From portals-pluto with Apache License 2.0 5 votes vote down vote up
@Override
public Collection<Part> getParts() throws IOException, ServletException {

	if (portletRequest instanceof ClientDataRequest) {
		try {
			return ((ClientDataRequest)portletRequest).getParts();
		}
		catch (PortletException e) {
			throw new ServletException(e);
		}
	}

	return null;
}
 
Example #30
Source File: HandleHttpRequest.java    From nifi with Apache License 2.0 5 votes vote down vote up
private FlowFile savePartAttributes(ProcessContext context, ProcessSession session, Part part, FlowFile flowFile, final int i, final int allPartsCount) {
  final Map<String, String> attributes = new HashMap<>();
  for (String headerName : part.getHeaderNames()) {
    final String headerValue = part.getHeader(headerName);
    putAttribute(attributes, "http.headers.multipart." + headerName, headerValue);
  }
  putAttribute(attributes, "http.multipart.size", part.getSize());
  putAttribute(attributes, "http.multipart.content.type", part.getContentType());
  putAttribute(attributes, "http.multipart.name", part.getName());
  putAttribute(attributes, "http.multipart.filename", part.getSubmittedFileName());
  putAttribute(attributes, "http.multipart.fragments.sequence.number", i+1);
  putAttribute(attributes, "http.multipart.fragments.total.number", allPartsCount);
  return session.putAllAttributes(flowFile, attributes);
}