我需要从用户上传的Word文档中提取文本。我得到了code来从位于我的m / c上的文档中提取单词。但是我的要求是允许用户使用上载按钮上载自己的文档并阅读该文档(我不需要保存该文档)。您能建议我该怎么做吗?我需要知道单击“上传”按钮后需要执行的所有操作。

最佳答案

用户上载文件时,请抓住关联的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...
    }
}

关于java - 上载Word文件,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/5431757/

10-12 06:22