【问题标题】:Upload word document上传word文档
【发布时间】:2014-04-10 00:19:41
【问题描述】:

我需要从用户上传的word文档中提取文本。我得到了code 来从我的 m/c 上的文档中提取单词。但我的要求是允许用户使用上传按钮上传自己的文档并阅读该文档(我不需要保存该文档)。你能建议我怎么做吗?我需要知道点击上传按钮后所有需要发生的事情。

【问题讨论】:

  • 哪个上传按钮?你在使用任何 MVC 框架吗?
  • 您可以通过searching for related tags找到相关问答。
  • 我正在使用 servlet,上传按钮看起来像

    请指定一个文件或一组文件:

标签: java ms-word apache-poi


【解决方案1】:

当用户上传他们的文件时,获取关联的InputStream 并将其存储到一个变量中,例如inputStream。然后就拿示例代码,并替换这一行:

fs = new POIFSFileSystem(new FileInputStream(filesname));

...类似于:

fs = new POIFSFileSystem(inputStream); 

应该足够简单,假设您已经有一个Servlet 来处理上传。

编辑:

假设您使用commons-fileupload 解析上传,以下是 servlet 如何工作的基础知识:

public class UploadServlet extends HttpServlet {
    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        // Create a factory for disk-based file items
        FileItemFactory factory = new DiskFileItemFactory();

        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);

        // Parse the request
        List<FileItem> items = upload.parseRequest(request);

        //this assumes that the uploaded file is the only thing submitted by the form
        //if not you need to iterate the list and find it
        FileItem wordFile = items.get(0);

        //get a stream that can be used to read the uploaded file
        InputStream inputStream = wordFile.getInputStream();

        //and the rest you already know...
    }
}

【讨论】:

  • 太棒了。您能告诉我如何获取上传到我的 servlet 中的文件的 InputStream。谢谢!
  • 我在网上搜索 InputStream 并得到类似的东西InputStream input = new FileInputStream("c:\\data\\input-text.txt"); 这也是从固定位置读取文件
  • @dazzle - 我已经用一些示例代码更新了帖子,希望对您有所帮助。
  • 非常感谢!非常感谢您的帮助
猜你喜欢
  • 1970-01-01
  • 2022-01-23
  • 1970-01-01
  • 2011-09-15
  • 2020-11-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多