apache common之文件上传

依赖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;
	}

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。