如何使用commons文件上传流式api上传文件 [英] how to upload a file using commons file upload streaming api

查看:119
本文介绍了如何使用commons文件上传流式api上传文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在关注commons文件上传站点中提供的有关流API的示例。我不知道如何弄清楚如何获取上传文件的文件扩展名,如何将文件写入目录,最糟糕的部分是编写示例注释的人 //处理输入流... 它让我想知道它是否是如此微不足道,以至于我是唯一一个不知道如何做的人。

I am following the example provided in the commons file upload site about streaming API. I am stuck trying to figure out how to get the file extension of the uploaded file, how to write the file to a directory and the worst part is where the person who wrote the example comments // Process the input stream... It leaves me wondering if it's something so trivial that I'm the only one who doesn't know how to.

推荐答案

在HTML文件中使用此项:

Use this in your HTML file:

<form action="UploadController" enctype="multipart/form-data" method="post">  
  <input type="file">  
</form>

以及 UploadController servlet,在 doPost 方法:

and in the UploadController servlet, inside the doPost method:

    boolean isMultipart = ServletFileUpload.isMultipartContent(request);

    if (isMultipart) {
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);

    try {
        List items = upload.parseRequest(request);
        Iterator iterator = items.iterator();
        while (iterator.hasNext()) {
            FileItem item = (FileItem) iterator.next();

            if (!item.isFormField()) {
                String fileName = item.getName();

                String root = getServletContext().getRealPath("/");
                File path = new File(root + "/uploads");
                if (!path.exists()) {
                    boolean status = path.mkdirs();
                }

                File uploadedFile = new File(path + "/" + fileName);
                System.out.println(uploadedFile.getAbsolutePath());
                item.write(uploadedFile);
            }
        }
    } catch (FileUploadException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

这篇关于如何使用commons文件上传流式api上传文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆