1.导入相应的jar包
在这里我是用Maven导入相应的jar包。当然也可以在网上寻找commons-io-2.0.1.jar和commons-fileupload-1.2.2.jar包。
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.0.1</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.2.2</version>
</dependency>
2.实现文件上传
写一个jsp文件
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>文件上传</title>
</head>
<body>
<div>
<!--
注意!表单的enctype属性一定要由原来的文本编码格式改成下面的二进制文本编码格式
在使用包含上传空间的表单时,必须使用该值 (multipart/form-data)
-->
<form action="${pageContext.request.contextPath}/user.action?method=uploadFile" method="post" enctype="multipart/form-data">
<h1>最基本的文件上传方式</h1>
<hr>
<fieldset>
<legend>文件上传</legend>
用户名:<input type="text" name="username">
<br>
<input type="file" name="file">
<br>
<input type="submit" value="提交">
</fieldset>
</form>
</div>
</body>
</html>
然后写一个后台的实现代码
/**
* 上传文件
* @param request
* @param response
*/
public void uploadFile(HttpServletRequest request,HttpServletResponse response) {
//判断编码方式是否为 multipart/form-data
boolean isMutipart = ServletFileUpload.isMultipartContent(request);
if(isMutipart) {
InputStream is = null;
FileOutputStream fos = null;
//用于处理文件上传
ServletFileUpload upload = new ServletFileUpload();
//解决上传文件名的中文乱码
upload.setHeaderEncoding("UTF-8");
try {
//从request中按顺序解析出数据
FileItemIterator iterator = upload.getItemIterator(request);
while(iterator.hasNext()) {
FileItemStream fis = iterator.next();
//创建一个输入流来获取fis中的数据,
//使用了Multipart之后就表示通过字节数据进行传输,所以需要将其转化为输入流进行处理
is = fis.openStream();
if(fis.isFormField()) {//判断是否为表单域
//是表单域就输出表单域的名称
System.out.println("属性名:"+fis.getFieldName());
//将流中的数据转化成String
System.out.println("数据:"+Streams.asString(is));
}else {//如果不是表单域,就说明是上传的文件
System.out.println("属性名:"+fis.getFieldName());
System.out.println("上传文件的路径名:"+fis.getName());
//获取真实路径
//String path = request.getSession().getServletContext().getRealPath("/fileSave");
//上传文件所保存的位置
String path = "E:\\log";
//获取文件名
String fileName = fis.getName().substring(fis.getName().lastIndexOf("\\")+1);
System.out.println(fileName);
path = path+"\\"+fileName;
System.out.println(path);
//将上传的文件写入到另外一个路径中
fos = new FileOutputStream(path);
byte [] buf = new byte[1024];
int length = 0;
while((length=is.read(buf))>0) {
fos.write(buf,0,length);
}
System.out.println();
}
}
} catch (FileUploadException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
if(is!=null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(fos!=null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
参考:
https://blog.csdn.net/sinat_28050007/article/details/53290321