apache common之文件上传

Junzizhiai 2014-11-25

依赖jar:

<dependency>
	<groupId>commons-fileupload</groupId>
	<artifactId>commons-fileupload</artifactId>
	<version>1.3.1</version>
</dependency>

采用fileupload组件进行上传,jsp页面:

<form name="upform" method="post" action="${basePath}data/upload" enctype="multipart/form-data">
	<table class="table table-striped">
		<tr>
			<th colspan="2" align="center">
				领客网linkrmb.com数据上传单
			</th>
		</tr>
		<tr>
			<td>
				用户账户(email):
			</td>
			<td>
				<input id="email" name="email" type="text" value="${item.email}">
			</td>
		</tr>
		<tr>
			<td>
				上传文件:
			</td>
			<td>
				<input name="file" type="file" size="20" >
			</td>
		</tr>

	</table>
	<center>
		<input  type="submit" value="提交">
		<input  type="reset" value="重置">
	</center>
</form>

对应的控制层的代码:

protected String storeFile(HttpServletRequest request, String baseDir)
			throws Exception {
		DiskFileItemFactory factory = new DiskFileItemFactory();
		ServletFileUpload upload = new ServletFileUpload(factory);
		List<FileItem> items = upload.parseRequest(request);
		Iterator<FileItem> itr = items.iterator();
		String file = "common_data_file_";
		while (itr.hasNext()) {
			FileItem item = (FileItem) itr.next();
			if (!item.isFormField()) {
				System.out.println("上传文件的大小:" + item.getSize());
				System.out.println("上传文件的类型:" + item.getContentType());
				System.out.println("上传文件的名称:" + item.getName());
				file = file + item.getFieldName();
				item.write(new File(baseDir + File.separator + file));
				break;
			}
		}
		return file;
	}

相关推荐

lionelf / 0评论 2020-07-28