Servlet自学之旅(9):文件上传

Servlet 文件上传

通过HTML的form标签,Servlet可以让我们将文件上传到服务器,包括文本文件,图片等形式的文档。

创建上传文件的表单

首先要创建一个jsp文件来上传表单,表单的相关属性需要符合以下几点:

  • method属性应设置为POST,不可使用GET
  • enctype属性应设置为multipart/form-data.
  • action属性应设置为在服务器上负责处理文件上传的Servlet。
  • 上传单个文件 使用单个 < input type=”file”…./>标签 ,多文件上传需要不同name的< input…/>,浏览器会为每个标签关联一个浏览按钮。

uploade.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>
<h1>文件上传</h1>
<form action="/UploadFile/UploadServlet" enctype="multipart/form-data">
选择上传的:
<input type="file" name="uploadOne"/>
<input type="submit" value="Submit"/>
</form>
</body>
</html>

创建接收文件的Servlet

@WebServlet("/UploadServlet")
public class UploadServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    // 接收后文件的存储目录
    private static final String UPLOAD_DIR = "upload";

    // 内存临界值 - 超过后将产生临时文件并存储于临时目录中
    private static final int MEMORY_THRESHOLD = 1024 * 1024 * 3; // 3MB
    // 上传文件的最大值
    private static final int MAX_FILE_SIZE = 1024 * 1024 * 40; // 40MB
    // 单次请求所包含的最大值 (上传的文件和表单等其他数据)
    private static final int MAX_REQUEST_SIZE = 1024 * 1024 * 50; // 50MB

    public UploadServlet() {
        super();
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 检测是否是多媒体上传
        if (!ServletFileUpload.isMultipartContent(request)) {
            // 不是的话就return,不进行之后接收上传文件的操作
            return;
        }

        // 设置上传相关的参数
        DiskFileItemFactory dItemFactory = new DiskFileItemFactory();
        dItemFactory.setSizeThreshold(MEMORY_THRESHOLD);

        // 设置临时存储目录
         dItemFactory.setRepository(new File(System.getProperty("java.io.tmpdir")));
        ServletFileUpload upload = new ServletFileUpload(dItemFactory);
        upload.setFileSizeMax(MAX_FILE_SIZE);
        upload.setSizeMax(MAX_REQUEST_SIZE);
        upload.setHeaderEncoding("UTF-8");

         // String uploadPath = request.getServletContext().getRealPath("./") + UPLOAD_DIR;
        // this.getServletConfig().getServletContext().getRealPath("/");
        // request.getServletContext().getRealPath("/");
        //文件存放的地址,上面注释的地址是Eclipse中获取的项目绝对地址:
     //G:\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\项目名
        //这个地址太深,不便查看,截取.metadata前的地址,放在项目文件的目录下。
        //以下地址:G:\workspace\UpLoadFile\WebContent\upload
        String t = Thread.currentThread().getContextClassLoader().getResource("").getPath();
        int num = t.indexOf(".metadata");
        String uploadPath = t.substring(1, num).replace('/', '\\') + "UploadFile\\WebContent\\" + UPLOAD_DIR;
        File uploadDir = new File(uploadPath);
        if (!uploadDir.exists()) {
            uploadDir.mkdirs();
        }

        try {
            @SuppressWarnings("unchecked")
            Map<String, List<FileItem>> fileMap = upload.parseParameterMap(request);
            fileMap.entrySet();
            Iterator iterator = fileMap.entrySet().iterator();
            if (iterator.hasNext()) {
                Map.Entry entry = (Entry) iterator.next();
                List<FileItem> fileItems = (List<FileItem>) entry.getValue();
                for (FileItem item : fileItems) {
                     //对传入的非 简单的字符串进行处理,即获取非表单字段的 ,比如说二进制的 图片,电影这些 
                    if (!item.isFormField()) {
                        String fileName = new File(item.getName()).getName();
                        String filePath = uploadPath + File.separator + fileName;
                        File storeFile = new File(filePath);
                        // 在控制台输出文件的上传路径
                        System.out.println("上传成功");
                        System.out.println(filePath);
                        // 保存文件到硬盘
                        item.write(storeFile);
                    }
                }
            }

        } catch (FileUploadException e) {
            System.out.println("上传失败");
            e.printStackTrace();
        } catch (Exception e) {
            System.out.println("上传失败");
            e.printStackTrace();
        }
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值