org.springframework.util.FileCopyUtils源码实例Demo

类org.springframework.util.FileCopyUtils源码实例Demo

下面列出了org.springframework.util.FileCopyUtils 类实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: youkefu   文件: IMAgentController.java
@RequestMapping("/adv/save")
  @Menu(type = "setting" , subtype = "adv" , admin= false)
  public ModelAndView advsave(ModelMap map , HttpServletRequest request , @Valid AdType adv , @Valid String advtype , @RequestParam(value = "imgfile", required = false) MultipartFile imgfile) throws IOException {
  	adv.setOrgi(super.getOrgi(request));
adv.setCreater(super.getUser(request).getId());
if(!StringUtils.isBlank(adv.getContent())){
	adv.setContent(adv.getContent().replaceAll("\"", "'"));
}
adv.setCreatetime(new Date());
if(imgfile!=null && imgfile.getSize() > 0){
	File adDir = new File(path , "adv");
  		if(!adDir.exists()){
  			adDir.mkdirs() ;
  		}
  		String fileName = "adv/"+UKTools.getUUID()+imgfile.getOriginalFilename().substring(imgfile.getOriginalFilename().lastIndexOf(".")) ;
  		FileCopyUtils.copy(imgfile.getBytes(), new File(path , fileName));
  		adv.setImgurl("/res/image.html?id="+java.net.URLEncoder.encode(fileName , "UTF-8"));
}
adTypeRes.save(adv) ;

UKTools.initAdv(super.getOrgi(request));

      return request(super.createRequestPageTempletResponse("redirect:/setting/adv.html?adpos="+adv.getAdpos()));
  }
 
private Class<?> doLoadClass(String name) throws ClassNotFoundException {
	String internalName = StringUtils.replace(name, ".", "/") + ".class";
	InputStream is = this.enclosingClassLoader.getResourceAsStream(internalName);
	if (is == null) {
		throw new ClassNotFoundException(name);
	}
	try {
		byte[] bytes = FileCopyUtils.copyToByteArray(is);
		bytes = applyTransformers(name, bytes);
		Class<?> cls = defineClass(name, bytes, 0, bytes.length);
		// Additional check for defining the package, if not defined yet.
		if (cls.getPackage() == null) {
			int packageSeparator = name.lastIndexOf('.');
			if (packageSeparator != -1) {
				String packageName = name.substring(0, packageSeparator);
				definePackage(packageName, null, null, null, null, null, null, null);
			}
		}
		this.classCache.put(name, cls);
		return cls;
	}
	catch (IOException ex) {
		throw new ClassNotFoundException("Cannot load resource for class [" + name + "]", ex);
	}
}
 
@Test
public void resourceInjection() throws IOException {
	System.setProperty("logfile", "do_not_delete_me.txt");
	try (AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(ResourceInjectionBean.class)) {
		ResourceInjectionBean resourceInjectionBean = ac.getBean(ResourceInjectionBean.class);
		Resource resource = new ClassPathResource("do_not_delete_me.txt");
		assertEquals(resource, resourceInjectionBean.resource);
		assertEquals(resource.getURL(), resourceInjectionBean.url);
		assertEquals(resource.getURI(), resourceInjectionBean.uri);
		assertEquals(resource.getFile(), resourceInjectionBean.file);
		assertArrayEquals(FileCopyUtils.copyToByteArray(resource.getInputStream()),
				FileCopyUtils.copyToByteArray(resourceInjectionBean.inputStream));
		assertEquals(FileCopyUtils.copyToString(new EncodedResource(resource).getReader()),
				FileCopyUtils.copyToString(resourceInjectionBean.reader));
	}
	finally {
		System.getProperties().remove("logfile");
	}
}
 
@Test
public void cachedContentWithOverflow() throws Exception {
	this.request.setMethod("GET");
	this.request.setCharacterEncoding(CHARSET);
	this.request.setContent("Hello World".getBytes(CHARSET));

	ContentCachingRequestWrapper wrapper = new ContentCachingRequestWrapper(this.request, 3) {
		@Override
		protected void handleContentOverflow(int contentCacheLimit) {
			throw new IllegalStateException(String.valueOf(contentCacheLimit));
		}
	};

	try {
		FileCopyUtils.copyToByteArray(wrapper.getInputStream());
		fail("Should have thrown IllegalStateException");
	}
	catch (IllegalStateException ex) {
		assertEquals("3", ex.getMessage());
	}
}
 
@Test
public void transformManifest() throws Exception {
	MockServerWebExchange exchange = MockServerWebExchange.from(get("/static/test.appcache"));
	Resource resource = getResource("test.appcache");
	Resource actual = this.transformer.transform(exchange, resource, this.chain).block(TIMEOUT);

	assertNotNull(actual);
	byte[] bytes = FileCopyUtils.copyToByteArray(actual.getInputStream());
	String content = new String(bytes, "UTF-8");

	assertThat("should rewrite resource links", content,
			containsString("/static/foo-e36d2e05253c6c7085a91522ce43a0b4.css"));
	assertThat("should rewrite resource links", content,
			containsString("/static/bar-11e16cf79faee7ac698c805cf28248d2.css"));
	assertThat("should rewrite resource links", content,
			containsString("/static/js/bar-bd508c62235b832d960298ca6c0b7645.js"));

	assertThat("should not rewrite external resources", content, containsString("//example.org/style.css"));
	assertThat("should not rewrite external resources", content, containsString("http://example.org/image.png"));

	// Not the same hash as Spring MVC
	// Hash is computed from links, and not from the linked content

	assertThat("should generate fingerprint", content,
			containsString("# Hash: 8eefc904df3bd46537fa7bdbbc5ab9fb"));
}
 
@Test
public void transformManifest() throws Exception {
	this.request = new MockHttpServletRequest("GET", "/static/test.appcache");
	Resource resource = getResource("test.appcache");
	Resource actual = this.transformer.transform(this.request, resource, this.chain);

	byte[] bytes = FileCopyUtils.copyToByteArray(actual.getInputStream());
	String content = new String(bytes, "UTF-8");

	assertThat("should rewrite resource links", content,
			containsString("/static/foo-e36d2e05253c6c7085a91522ce43a0b4.css"));
	assertThat("should rewrite resource links", content,
			containsString("/static/bar-11e16cf79faee7ac698c805cf28248d2.css"));
	assertThat("should rewrite resource links", content,
			containsString("/static/js/bar-bd508c62235b832d960298ca6c0b7645.js"));

	assertThat("should not rewrite external resources", content, containsString("//example.org/style.css"));
	assertThat("should not rewrite external resources", content, containsString("http://example.org/image.png"));

	assertThat("should generate fingerprint", content,
			containsString("# Hash: 4bf0338bcbeb0a5b3a4ec9ed8864107d"));
}
 
@Test  // SPR-12960
public void filterWriterWithDisabledCaching() throws Exception {
	final MockHttpServletRequest request = new MockHttpServletRequest("GET", "/hotels");
	MockHttpServletResponse response = new MockHttpServletResponse();

	final byte[] responseBody = "Hello World".getBytes("UTF-8");
	FilterChain filterChain = (filterRequest, filterResponse) -> {
		assertEquals("Invalid request passed", request, filterRequest);
		((HttpServletResponse) filterResponse).setStatus(HttpServletResponse.SC_OK);
		FileCopyUtils.copy(responseBody, filterResponse.getOutputStream());
	};

	ShallowEtagHeaderFilter.disableContentCaching(request);
	this.filter.doFilter(request, response, filterChain);

	assertEquals(200, response.getStatus());
	assertNull(response.getHeader("ETag"));
	assertArrayEquals(responseBody, response.getContentAsByteArray());
}
 
源代码8 项目: spring-analysis-note   文件: PassThroughClob.java
@Override
public InputStream getAsciiStream() throws SQLException {
	try {
		if (this.content != null) {
			return new ByteArrayInputStream(this.content.getBytes(StandardCharsets.US_ASCII));
		}
		else if (this.characterStream != null) {
			String tempContent = FileCopyUtils.copyToString(this.characterStream);
			return new ByteArrayInputStream(tempContent.getBytes(StandardCharsets.US_ASCII));
		}
		else {
			return (this.asciiStream != null ? this.asciiStream : StreamUtils.emptyInput());
		}
	}
	catch (IOException ex) {
		throw new SQLException("Failed to read stream content: " + ex);
	}
}
 
源代码9 项目: java-technology-stack   文件: PassThroughClob.java
@Override
public InputStream getAsciiStream() throws SQLException {
	try {
		if (this.content != null) {
			return new ByteArrayInputStream(this.content.getBytes(StandardCharsets.US_ASCII));
		}
		else if (this.characterStream != null) {
			String tempContent = FileCopyUtils.copyToString(this.characterStream);
			return new ByteArrayInputStream(tempContent.getBytes(StandardCharsets.US_ASCII));
		}
		else {
			return (this.asciiStream != null ? this.asciiStream : StreamUtils.emptyInput());
		}
	}
	catch (IOException ex) {
		throw new SQLException("Failed to read stream content: " + ex);
	}
}
 
@Test
public void payloadReader() throws Exception {
	filter.setIncludePayload(true);

	final MockHttpServletRequest request = new MockHttpServletRequest("POST", "/hotels");
	MockHttpServletResponse response = new MockHttpServletResponse();

	final String requestBody = "Hello World";
	request.setContent(requestBody.getBytes("UTF-8"));

	FilterChain filterChain = new FilterChain() {
		@Override
		public void doFilter(ServletRequest filterRequest, ServletResponse filterResponse)
				throws IOException, ServletException {
			((HttpServletResponse) filterResponse).setStatus(HttpServletResponse.SC_OK);
			String buf = FileCopyUtils.copyToString(filterRequest.getReader());
			assertEquals(requestBody, buf);
		}
	};

	filter.doFilter(request, response, filterChain);

	assertNotNull(filter.afterRequestMessage);
	assertTrue(filter.afterRequestMessage.contains(requestBody));
}
 
@Test
public void filterNoMatch() throws Exception {
	final MockHttpServletRequest request = new MockHttpServletRequest("GET", "/hotels");
	MockHttpServletResponse response = new MockHttpServletResponse();

	final byte[] responseBody = "Hello World".getBytes("UTF-8");
	FilterChain filterChain = (filterRequest, filterResponse) -> {
		assertEquals("Invalid request passed", request, filterRequest);
		((HttpServletResponse) filterResponse).setStatus(HttpServletResponse.SC_OK);
		FileCopyUtils.copy(responseBody, filterResponse.getOutputStream());
	};
	filter.doFilter(request, response, filterChain);

	assertEquals("Invalid status", 200, response.getStatus());
	assertEquals("Invalid ETag header", "\"0b10a8db164e0754105b7a99be72e3fe5\"", response.getHeader("ETag"));
	assertTrue("Invalid Content-Length header", response.getContentLength() > 0);
	assertArrayEquals("Invalid content", responseBody, response.getContentAsByteArray());
}
 
@Override
public void setClobAsCharacterStream(
		PreparedStatement ps, int paramIndex, @Nullable Reader characterStream, int contentLength)
		throws SQLException {

	if (characterStream != null) {
		Clob clob = ps.getConnection().createClob();
		try {
			FileCopyUtils.copy(characterStream, clob.setCharacterStream(1));
		}
		catch (IOException ex) {
			throw new DataAccessResourceFailureException("Could not copy into LOB stream", ex);
		}
		this.temporaryClobs.add(clob);
		ps.setClob(paramIndex, clob);
	}
	else {
		ps.setClob(paramIndex, (Clob) null);
	}

	if (logger.isDebugEnabled()) {
		logger.debug(characterStream != null ?
				"Copied character stream into temporary CLOB with length " + contentLength :
				"Set CLOB to null");
	}
}
 
@Override
protected ClientHttpResponse executeInternal(HttpHeaders headers, byte[] bufferedOutput) throws IOException {
	addHeaders(this.connection, headers);
	// JDK <1.8 doesn't support getOutputStream with HTTP DELETE
	if (getMethod() == HttpMethod.DELETE && bufferedOutput.length == 0) {
		this.connection.setDoOutput(false);
	}
	if (this.connection.getDoOutput() && this.outputStreaming) {
		this.connection.setFixedLengthStreamingMode(bufferedOutput.length);
	}
	this.connection.connect();
	if (this.connection.getDoOutput()) {
		FileCopyUtils.copy(bufferedOutput, this.connection.getOutputStream());
	}
	else {
		// Immediately trigger the request in a no-output scenario as well
		this.connection.getResponseCode();
	}
	return new SimpleClientHttpResponse(this.connection);
}
 
源代码14 项目: code   文件: MyProxy.java
/**
 * @param proxyClassString 代理类的代码
 * @param myProxyFile 代理类的Java文件
 * @throws IOException
 */
private static void compile(StringBuffer proxyClassString, File myProxyFile) throws IOException {
    // in out
    FileCopyUtils.copy(proxyClassString.toString().getBytes(), myProxyFile);
    // 调用系统编译器
    JavaCompiler javaCompiler = ToolProvider.getSystemJavaCompiler();

    StandardJavaFileManager standardJavaFileManager = javaCompiler.getStandardFileManager(null, null, null);

    Iterable javaFileObjects = standardJavaFileManager.getJavaFileObjects(myProxyFile);

    JavaCompiler.CompilationTask task = javaCompiler.getTask(null, standardJavaFileManager, null, null, null, javaFileObjects);

    task.call();

    standardJavaFileManager.close();
}
 
@Test
public void getBodyViaRequestParameterWithRequestEncoding() throws Exception {
	MockMultipartHttpServletRequest mockRequest = new MockMultipartHttpServletRequest() {
		@Override
		public HttpHeaders getMultipartHeaders(String paramOrFileName) {
			HttpHeaders headers = new HttpHeaders();
			headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
			return headers;
		}
	};

	byte[] bytes = {(byte) 0xC4};
	mockRequest.setParameter("part", new String(bytes, StandardCharsets.ISO_8859_1));
	mockRequest.setCharacterEncoding("iso-8859-1");
	ServerHttpRequest request = new RequestPartServletServerHttpRequest(mockRequest, "part");
	byte[] result = FileCopyUtils.copyToByteArray(request.getBody());
	assertArrayEquals(bytes, result);
}
 
@Test
public void filterMatch() throws Exception {
	final MockHttpServletRequest request = new MockHttpServletRequest("GET", "/hotels");
	String etag = "\"0b10a8db164e0754105b7a99be72e3fe5\"";
	request.addHeader("If-None-Match", etag);
	MockHttpServletResponse response = new MockHttpServletResponse();

	FilterChain filterChain = (filterRequest, filterResponse) -> {
		assertEquals("Invalid request passed", request, filterRequest);
		byte[] responseBody = "Hello World".getBytes("UTF-8");
		FileCopyUtils.copy(responseBody, filterResponse.getOutputStream());
		filterResponse.setContentLength(responseBody.length);
	};
	filter.doFilter(request, response, filterChain);

	assertEquals("Invalid status", 304, response.getStatus());
	assertEquals("Invalid ETag header", "\"0b10a8db164e0754105b7a99be72e3fe5\"", response.getHeader("ETag"));
	assertFalse("Response has Content-Length header", response.containsHeader("Content-Length"));
	assertArrayEquals("Invalid content", new byte[0], response.getContentAsByteArray());
}
 
@Test
public void filterNoMatch() throws Exception {
	final MockHttpServletRequest request = new MockHttpServletRequest("GET", "/hotels");
	MockHttpServletResponse response = new MockHttpServletResponse();

	final byte[] responseBody = "Hello World".getBytes("UTF-8");
	FilterChain filterChain = (filterRequest, filterResponse) -> {
		assertEquals("Invalid request passed", request, filterRequest);
		((HttpServletResponse) filterResponse).setStatus(HttpServletResponse.SC_OK);
		FileCopyUtils.copy(responseBody, filterResponse.getOutputStream());
	};
	filter.doFilter(request, response, filterChain);

	assertEquals("Invalid status", 200, response.getStatus());
	assertEquals("Invalid ETag header", "\"0b10a8db164e0754105b7a99be72e3fe5\"", response.getHeader("ETag"));
	assertTrue("Invalid Content-Length header", response.getContentLength() > 0);
	assertArrayEquals("Invalid content", responseBody, response.getContentAsByteArray());
}
 
@Test
public void filterMatch() throws Exception {
	final MockHttpServletRequest request = new MockHttpServletRequest("GET", "/hotels");
	String etag = "\"0b10a8db164e0754105b7a99be72e3fe5\"";
	request.addHeader("If-None-Match", etag);
	MockHttpServletResponse response = new MockHttpServletResponse();

	FilterChain filterChain = (filterRequest, filterResponse) -> {
		assertEquals("Invalid request passed", request, filterRequest);
		byte[] responseBody = "Hello World".getBytes("UTF-8");
		FileCopyUtils.copy(responseBody, filterResponse.getOutputStream());
		filterResponse.setContentLength(responseBody.length);
	};
	filter.doFilter(request, response, filterChain);

	assertEquals("Invalid status", 304, response.getStatus());
	assertEquals("Invalid ETag header", "\"0b10a8db164e0754105b7a99be72e3fe5\"", response.getHeader("ETag"));
	assertFalse("Response has Content-Length header", response.containsHeader("Content-Length"));
	assertArrayEquals("Invalid content", new byte[0], response.getContentAsByteArray());
}
 
@Test
public void filterWriter() throws Exception {
	final MockHttpServletRequest request = new MockHttpServletRequest("GET", "/hotels");
	String etag = "\"0b10a8db164e0754105b7a99be72e3fe5\"";
	request.addHeader("If-None-Match", etag);
	MockHttpServletResponse response = new MockHttpServletResponse();

	FilterChain filterChain = (filterRequest, filterResponse) -> {
		assertEquals("Invalid request passed", request, filterRequest);
		((HttpServletResponse) filterResponse).setStatus(HttpServletResponse.SC_OK);
		String responseBody = "Hello World";
		FileCopyUtils.copy(responseBody, filterResponse.getWriter());
	};
	filter.doFilter(request, response, filterChain);

	assertEquals("Invalid status", 304, response.getStatus());
	assertEquals("Invalid ETag header", "\"0b10a8db164e0754105b7a99be72e3fe5\"", response.getHeader("ETag"));
	assertFalse("Response has Content-Length header", response.containsHeader("Content-Length"));
	assertArrayEquals("Invalid content", new byte[0], response.getContentAsByteArray());
}
 
@Test
public void payloadReader() throws Exception {
	filter.setIncludePayload(true);

	final MockHttpServletRequest request = new MockHttpServletRequest("POST", "/hotels");
	MockHttpServletResponse response = new MockHttpServletResponse();

	final String requestBody = "Hello World";
	request.setContent(requestBody.getBytes(StandardCharsets.UTF_8));

	FilterChain filterChain = (filterRequest, filterResponse) -> {
		((HttpServletResponse) filterResponse).setStatus(HttpServletResponse.SC_OK);
		String buf = FileCopyUtils.copyToString(filterRequest.getReader());
		assertEquals(requestBody, buf);
	};

	filter.doFilter(request, response, filterChain);

	assertNotNull(filter.afterRequestMessage);
	assertTrue(filter.afterRequestMessage.contains(requestBody));
}
 
@Test
public void payloadMaxLength() throws Exception {
	filter.setIncludePayload(true);
	filter.setMaxPayloadLength(3);

	final MockHttpServletRequest request = new MockHttpServletRequest("POST", "/hotels");
	MockHttpServletResponse response = new MockHttpServletResponse();

	final byte[] requestBody = "Hello World".getBytes(StandardCharsets.UTF_8);
	request.setContent(requestBody);

	FilterChain filterChain = (filterRequest, filterResponse) -> {
		((HttpServletResponse) filterResponse).setStatus(HttpServletResponse.SC_OK);
		byte[] buf = FileCopyUtils.copyToByteArray(filterRequest.getInputStream());
		assertArrayEquals(requestBody, buf);
		ContentCachingRequestWrapper wrapper =
				WebUtils.getNativeRequest(filterRequest, ContentCachingRequestWrapper.class);
		assertArrayEquals("Hel".getBytes(StandardCharsets.UTF_8), wrapper.getContentAsByteArray());
	};

	filter.doFilter(request, response, filterChain);

	assertNotNull(filter.afterRequestMessage);
	assertTrue(filter.afterRequestMessage.contains("Hel"));
	assertFalse(filter.afterRequestMessage.contains("Hello World"));
}
 
@Test(expected = UnsupportedOperationException.class)
public void headersAfterExecute() throws Exception {
	ClientHttpRequest request = factory.createRequest(new URI(baseUrl + "/status/ok"), HttpMethod.POST);

	request.getHeaders().add("MyHeader", "value");
	byte[] body = "Hello World".getBytes("UTF-8");
	FileCopyUtils.copy(body, request.getBody());

	ClientHttpResponse response = request.execute();
	try {
		request.getHeaders().add("MyHeader", "value");
	}
	finally {
		response.close();
	}
}
 
@Test
public void filterSendErrorMessage() throws Exception {
	final MockHttpServletRequest request = new MockHttpServletRequest("GET", "/hotels");
	MockHttpServletResponse response = new MockHttpServletResponse();

	final byte[] responseBody = "Hello World".getBytes("UTF-8");
	FilterChain filterChain = (filterRequest, filterResponse) -> {
		assertEquals("Invalid request passed", request, filterRequest);
		response.setContentLength(100);
		FileCopyUtils.copy(responseBody, filterResponse.getOutputStream());
		((HttpServletResponse) filterResponse).sendError(HttpServletResponse.SC_FORBIDDEN, "ERROR");
	};
	filter.doFilter(request, response, filterChain);

	assertEquals("Invalid status", 403, response.getStatus());
	assertNull("Invalid ETag header", response.getHeader("ETag"));
	assertEquals("Invalid Content-Length header", 100, response.getContentLength());
	assertArrayEquals("Invalid content", responseBody, response.getContentAsByteArray());
	assertEquals("Invalid error message", "ERROR", response.getErrorMessage());
}
 
@Test
public void read() throws IOException {
	Resource logo = new ClassPathResource("logo.jpg", BufferedImageHttpMessageConverterTests.class);
	byte[] body = FileCopyUtils.copyToByteArray(logo.getInputStream());
	MockHttpInputMessage inputMessage = new MockHttpInputMessage(body);
	inputMessage.getHeaders().setContentType(new MediaType("image", "jpeg"));
	BufferedImage result = converter.read(BufferedImage.class, inputMessage);
	assertEquals("Invalid height", 500, result.getHeight());
	assertEquals("Invalid width", 750, result.getWidth());
}
 
源代码25 项目: smart-admin   文件: FileServiceQiNiuYun.java
/**
 * 获取文件
 */
public File getFile(String key, String fileName) {
    String finalUrl = getDownloadUrl(key);
    OkHttpClient client = new OkHttpClient();
    Request req = new Request.Builder().url(finalUrl).build();
    okhttp3.Response resp = null;
    File file = new File(fileName);
    try {
        resp = client.newCall(req).execute();
        if (resp.isSuccessful()) {
            ResponseBody body = resp.body();
            InputStream objectContent = body.byteStream();
            // 输入流转换为字节流
            byte[] buffer = FileCopyUtils.copyToByteArray(objectContent);
            // 字节流写入文件
            FileCopyUtils.copy(buffer, file);
            // 关闭输入流
            objectContent.close();
        }

    } catch (IOException e) {
        log.error("文件获取失败:" + e);
        return null;
    } finally {
    }
    return file;
}
 
@Override
public String getScriptAsString() throws IOException {
	synchronized (this.lastModifiedMonitor) {
		this.lastModified = retrieveLastModifiedTime();
	}
	Reader reader = this.resource.getReader();
	return FileCopyUtils.copyToString(reader);
}
 
@Override
public void transferTo(File dest) throws IOException, IllegalStateException {
	this.part.write(dest.getPath());
	if (dest.isAbsolute() && !dest.exists()) {
		// Servlet 3.0 Part.write is not guaranteed to support absolute file paths:
		// may translate the given path to a relative location within a temp dir
		// (e.g. on Jetty whereas Tomcat and Undertow detect absolute paths).
		// At least we offloaded the file from memory storage; it'll get deleted
		// from the temp dir eventually in any case. And for our user's purposes,
		// we can manually copy it to the requested location as a fallback.
		FileCopyUtils.copy(this.part.getInputStream(), Files.newOutputStream(dest.toPath()));
	}
}
 
源代码28 项目: spring-cloud-yes   文件: FileUploadController.java
/**
 * 上传文件
 * 测试方法:
 * 使用命令:curl -F "[email protected]文件全名" localhost:8050/upload
 * ps.该示例比较简单,没有做IO异常、文件大小、文件非空等处理
 *
 * @param file 待上传的文件
 * @return 文件在服务器上的绝对路径
 * @throws IOException IO异常
 */
@RequestMapping(value = "/upload", method = RequestMethod.POST)
public @ResponseBody
String handleFileUpload(@RequestPart(value = "file") MultipartFile file) throws IOException {
    byte[] bytes = file.getBytes();
    File fileToSave = new File(
            Objects.requireNonNull(file.getOriginalFilename())
    );
    FileCopyUtils.copy(bytes, fileToSave);
    return fileToSave.getAbsolutePath();
}
 
@Test
public void getResourceVersion() throws Exception {
	Resource expected = new ClassPathResource("test/bar.css", getClass());
	String hash = DigestUtils.md5DigestAsHex(FileCopyUtils.copyToByteArray(expected.getInputStream()));

	assertEquals(hash, this.strategy.getResourceVersion(expected).block());
}
 
private void doTestMultipartHttpServletRequest(MultipartHttpServletRequest request) throws IOException {
	Set<String> fileNames = new HashSet<>();
	Iterator<String> fileIter = request.getFileNames();
	while (fileIter.hasNext()) {
		fileNames.add(fileIter.next());
	}
	assertEquals(2, fileNames.size());
	assertTrue(fileNames.contains("file1"));
	assertTrue(fileNames.contains("file2"));
	MultipartFile file1 = request.getFile("file1");
	MultipartFile file2 = request.getFile("file2");
	Map<String, MultipartFile> fileMap = request.getFileMap();
	List<String> fileMapKeys = new LinkedList<>(fileMap.keySet());
	assertEquals(2, fileMapKeys.size());
	assertEquals(file1, fileMap.get("file1"));
	assertEquals(file2, fileMap.get("file2"));

	assertEquals("file1", file1.getName());
	assertEquals("", file1.getOriginalFilename());
	assertNull(file1.getContentType());
	assertTrue(ObjectUtils.nullSafeEquals("myContent1".getBytes(), file1.getBytes()));
	assertTrue(ObjectUtils.nullSafeEquals("myContent1".getBytes(),
		FileCopyUtils.copyToByteArray(file1.getInputStream())));
	assertEquals("file2", file2.getName());
	assertEquals("myOrigFilename", file2.getOriginalFilename());
	assertEquals("text/plain", file2.getContentType());
	assertTrue(ObjectUtils.nullSafeEquals("myContent2".getBytes(), file2.getBytes()));
	assertTrue(ObjectUtils.nullSafeEquals("myContent2".getBytes(),
		FileCopyUtils.copyToByteArray(file2.getInputStream())));
}
 
源代码评论
动弹
沙发等你来抢
 类所在包
 类方法
 同包方法