JavaWeb 文件上传和下载
首先去apache官网下载commons-io.jar和commons-fileupload.jar,下载后导入到项目中去
apache官网都有相关文档,左侧的user guide 有关于上传下载实现的相关代码
upload.html
enctype="multipart/form-data"必须加上
<form action="uploadServlet?action=upload" method="post" enctype="multipart/form-data">
<input type="file" name="filename" id="filename"/><br/>
<input type="submit"/>
</form>
uploadServlet.java
public class UploadServlet extends HttpServlet{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// TODO Auto-generated method stub
doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
resp.setCharacterEncoding("utf-8");
String action = req.getParameter("action");
ServletContext servletContext = null;
String realPath = null; //图片文件夹路径
PrintWriter pw = null;
switch(action) {
//文件上传
case "upload":
DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
//配置临时存储库
servletContext = this.getServletConfig().getServletContext();
File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
diskFileItemFactory.setRepository(repository);
//创建文件上传程序对象
ServletFileUpload upload = new ServletFileUpload(diskFileItemFactory);
List<FileItem> items = null;
try {
//解析request发送的请求
items = upload.parseRequest(req);
} catch (FileUploadException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Iterator<FileItem> iterator = items.iterator();
while(iterator.hasNext()) {
FileItem item = iterator.next();
if(item.isFormField()) {
//表单内容
}else {
//表单文件流内容
String fieldName = item.getFieldName();
String fileName = item.getName();
String contextType = item.getContentType();
//判断item是否在内存中
boolean isInMemory = item.isInMemory();
//获取item的大小
long sizeInBytes = item.getSize();
//系统毫秒数作每个文件的唯一标识符
long seconds = System.currentTimeMillis();
//获取文件后缀名
String fileType = fileName.substring(fileName.lastIndexOf('.'), fileName.length());
//设置文件上传的位置
//servletContext.getRealPah() 获取服务器上真实绝对路径
//通过系统时间生成唯一的文件名,存储在up文件夹下
String FileWay = servletContext.getRealPath("/up/")+seconds+fileType;
File uploadFile = new File(FileWay);
try {
//将文件上传至指定文件夹
item.write(uploadFile);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
break;
//文件下载
case "download":
String filename = req.getParameter("filename");
System.out.println(filename);
//下载文件保存到本地的名称
resp.setHeader("content-disposition", "attachment;filename="+URLEncoder.encode(filename,"utf-8"));
OutputStream outputStream = resp.getOutputStream();
servletContext = this.getServletContext();
String realpath = servletContext.getRealPath("/");
//filename要和tomcat中上传文件夹中的文件名保持一致,否则会出现FileNotFoundException
FileInputStream fileInputStream = new FileInputStream(realpath+filename);
byte[] b = new byte[1024];
int i;
while((i=fileInputStream.read(b,0,b.length))!= -1) {
outputStream.write(b);
b = new byte[1024];
}
fileInputStream.close();
outputStream.flush();
outputStream.close();
break;
default:
break;
}
}
}
注意:上传文件是使用的是文件在本地的绝对路径,下载文件时使用的是文件在服务器中的相对路径,文件存储在tomcat服务器中的一个文件夹中而不是项目中的文件夹,访问该文件夹可以通过servletContext.getRealPah() 获取服务器上真实绝对路径