基于SpringMVC使用fileupload上传文件

1  通过pom或者其他方式加载jar包,需要导入两个包。

2  注意spring-mvc.xml文件要进行配置,配置如下:

<bean id="multipartResolver" 
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver">

3 然后就是前端代码了;注意类型就好了。

<form action="file/text" method="post" enctype="multipart/form-data">
					<div class="col-md-6 col-sm-12">
						<div class="block">


							<div class="form-group">
								<input id="file0" name="file0" type="file" multiple class="file"
									 data-show-caption="true">
							</div>

4  看后台操作(使用IO)

public String text(@RequestParam(value = "file0",required = false) CommonsMultipartFile file, HttpServletRequest request,
			HttpServletResponse response) throws Exception {

		String filepath = request.getSession().getServletContext().getRealPath("");// 获取请求文件在服务器下的路径

		// 为每个用户(进行提交的)创建临时唯一文件夹
		File dir = new File(filepath + "/temporary");
		if (!dir.exists()) {
			dir.mkdirs(); // 创建临时文件夹
		}
		String username = UUID.randomUUID().toString();// 创建全球唯一UUID;
		dir = new File(filepath + "/temporary/" + username);
		if (!dir.exists()) {
			dir.mkdirs(); // 创建用户文件夹
		}

		System.out.println("创建成功"+username);

		String ppath =filepath + "/temporary/" + username;

		try {
			// 获取输出流
			OutputStream os = new FileOutputStream(ppath  + "/test_file"  + ".txt");
			// 获取输入流CommonsMultipartFile中可以直接得到文件的流
			InputStream is = file.getInputStream();
			int temp;
			// 一个一个字节的读取并写入
			while ((temp = is.read()) != (-1)) {
				os.write(temp);
			}
			os.flush();
			os.close();
			is.close();
		} catch (Exception e) {
			e.printStackTrace();
		}

猜你喜欢

转载自blog.csdn.net/So_that/article/details/82748302