准备阶段,下载需要的包:
在Servlet中进行文件上传需要用到外部的类库,apache提供了这些类库, 主要需要commons-fileupload.jar和commons-io.jar
下载的步骤如下:
进入www.apache.org网站, ——>在Projects下找到commons,点击进入——>找到Components下的FileUpload,点击进入就可以找到下载
页面如下:
可以看到这里有开发指南和下载地址,如果要详细学习,慢慢看这里的资源就可以了。
commons-io.jar包的下载地址:http://commons.apache.org/fileupload/dependencies.html
把两个jar包放到WEB-INF的lib目录下。
开发阶段:
上传页面:index.jsp
- <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
- <%
- String path = request.getContextPath();
- String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
- %>
- <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
- <html>
- <head>
- <base href="<%=basePath%>">
- <title>文件上传</title>
- <meta http-equiv="pragma" content="no-cache">
- <meta http-equiv="cache-control" content="no-cache">
- <meta http-equiv="expires" content="0">
- <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
- <meta http-equiv="description" content="This is my page">
- <!--
- <link rel="stylesheet" type="text/css" href="styles.css">
- -->
- </head>
- <body>
- <form action="upload" method="post" enctype="multipart/form-data">
- 文件别名:<input type="text" name="filename"><br>
- 选择文件:<input type="file" name="fileupload"><br>
- <input type="submit" value="提交">
- </form>
- </body>
- </html>
这里注意第24行,上传文件时要指定提交方法method="post", 信息类型为enctype="multipart/form-data"
上传功能servlet:FileUpload
- package com.sunflower.servlet;
- import java.io.File;
- import java.io.IOException;
- import java.util.Iterator;
- import java.util.List;
- import javax.servlet.ServletException;
- import javax.servlet.http.HttpServlet;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- import org.apache.commons.fileupload.FileItem;
- import org.apache.commons.fileupload.FileItemFactory;
- import org.apache.commons.fileupload.FileUploadException;
- import org.apache.commons.fileupload.disk.DiskFileItemFactory;
- import org.apache.commons.fileupload.servlet.ServletFileUpload;
- public class FileUpload extends HttpServlet {
- protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
- req.setCharacterEncoding("UTF-8");
- fileControl(req, resp);
- }
- /**
- * 上传文件的处理
- */
- private void fileControl(HttpServletRequest req, HttpServletResponse resp) throws ServletException {
- // 在解析请求之前先判断请求类型是否为文件上传类型
- boolean isMultipart = ServletFileUpload.isMultipartContent(req);
- // 文件上传处理工厂
- FileItemFactory factory = new DiskFileItemFactory();
- // 创建文件上传处理器
- ServletFileUpload upload = new ServletFileUpload(factory);
- // 开始解析请求信息
- List items = null;
- try {
- items = upload.parseRequest(req);
- }
- catch (FileUploadException e) {
- e.printStackTrace();
- }
- // 对所有请求信息进行判断
- Iterator iter = items.iterator();
- while (iter.hasNext()) {
- FileItem item = (FileItem) iter.next();
- // 信息为普通的格式
- if (item.isFormField()) {
- String fieldName = item.getFieldName();
- String value = item.getString();
- req.setAttribute(fieldName, value);
- }
- // 信息为文件格式
- else {
- String fileName = item.getName();
- int index = fileName.lastIndexOf("//");
- fileName = fileName.substring(index + 1);
- req.setAttribute("realFileName", fileName);
- // 将文件写入
- // String path = req.getContextPath();
- // String directory = "uploadFile";
- // String basePath = req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort() + path + "/" + directory;
- String basePath = req.getRealPath("/uploadFile");
- File file = new File(basePath, fileName);
- try {
- item.write(file);
- }
- catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
- try {
- req.getRequestDispatcher("/uploadsuccess.jsp").forward(req, resp);
- }
- catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
这里要注意第66~68行,将文件上传到Web项目的"uploadFile"文件夹中,如果用这种方法得到的路径是"http://localhost:8080/upload/uploadFile", 而创建File类用的路径是绝对路径,这样就会出问题,所以这里要用的是得到真实路径的方法HttpServletRequest.getRealPath().
以上是最简单的文件上传,如果要加入上传的限制可以在DiskFileItemFactory和ServletFileUpload中进行限制:
在34行后加入:
- //创建临时文件目录
- File tempFile = new File(req.getRealPath("/temp"));
- //设置缓存大小
- ((DiskFileItemFactory) factory).setSizeThreshold(1024*1024);
- //设置临时文件存放地点
- ((DiskFileItemFactory) factory).setRepository(tempFile);
注意第72行的FileItem.write()方法,如果使用了这个方法写入文件,那么临时文件会被系统自动删除.
在38行后加入:
- //将页面请求传递信息最大值设置为50M
- upload.setSizeMax(1024*1024*50);
- //将单个上传文件信息最大值设置为6M
- upload.setFileSizeMax(1024*1024*6);