上传word文档

时间:2011-03-25 11:23:59

标签: java ms-word apache-poi

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

1 个答案:

答案 0 :(得分:1)

当用户上传文件时,请抓取关联的InputStream并将其存储到变量,例如inputStream。然后只需获取示例代码,并替换此行:

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

...有类似的东西:

fs = new POIFSFileSystem(inputStream); 

应该很简单,假设您已经有Servlet来处理上传。

编辑:

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

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...
    }
}