java - 从 InputStream 或 Byte 数组构造 DataSource

标签 java servlets apache-commons

我正在编写一个小文件上传实用程序,作为一个更大项目的一部分。最初我是使用 Apache commons File 实用程序类从 servlet 处理这个问题。这是我为该服务编写的快速测试客户端的片段:

public static void main(String[] args) {

  JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean();

 factory.getInInterceptors().add(new LoggingInInterceptor());
 factory.getOutInterceptors().add(new LoggingOutInterceptor());
 factory.setServiceClass(FileUploadService.class);
 factory.setAddress("http://localhost:8080/FileUploadService/FileUploadService");
 FileUploadService client = (FileUploadService) factory.create();

 FileType file = new FileType();
 file.setName("statemo_1256144312279");
 file.setType("xls");

 DataSource source = new FileDataSource(new File("c:/development/statemo_1256144312279.xls"));
 file.setHandler(new DataHandler(source));
 Boolean ret = client.uploadFile(file);
 System.out.println (ret);
 System.exit(0);

这绝对没问题。现在,当我试图替换 Apache 公共(public)实用程序时,问题就来了。在上面的代码中,我从一个具有绝对路径名的文件创建了一个数据源。在我的 servlet 中,我无法获得绝对路径名,而且我通过线路发送的文件是空的。

这是 servlet 代码:

 @SuppressWarnings("unchecked")
    protected void doPost (final HttpServletRequest request, final HttpServletResponse response) 
        throws ServletException, IOException {

    // form should have enctype="multipart/form-data" as an attribute
 if (!ServletFileUpload.isMultipartContent (request)) {
  LOG.info("Invalid form attribute");
  return;
 }

 //DataInputStream in = new DataInputStream(request.getInputStream());

 final DiskFileItemFactory factory = new DiskFileItemFactory ();
 factory.setSizeThreshold(FILE_THRESHOLD_SIZE);

 final ServletFileUpload sfu = new ServletFileUpload (factory);
 sfu.setSizeMax(MAX_FILE_SIZE);

 final HttpSession session = request.getSession();

 final List<FileItem> files = new ArrayList<FileItem>();

 final List<String> filesToProcess = new ArrayList<String>();

 try {
        final List<FileItem> items = sfu.parseRequest(request);

        for (final FileItem f : items) {
            if (!f.isFormField())
                files.add(f);
        }

        /*for (final FileItem f : files) {
         final String absoluteFileName = UPLOAD_DESTINATION + FilenameUtils.getName(f.getName());

            //f.write(new File (absoluteFileName));
            filesToProcess.add(absoluteFileName);
        }*/

        FileItem f = files.get(0);

        LOG.info("File: " + FilenameUtils.getName(f.getName()));
        LOG.info("FileBaseName: " + FilenameUtils.getBaseName(f.getName()));
        LOG.info("FileExtension: " + FilenameUtils.getExtension(f.getName()));

        FileUploadServiceClient client = new FileUploadServiceClient();

        DataSource source = new FileDataSource(new File(f.getName()));

        FileType file = new FileType();
        file.setHandler(new DataHandler(source));
        file.setName(FilenameUtils.getBaseName(f.getName()));
        file.setType(FilenameUtils.getExtension(f.getName()));

        Boolean ret = client.uploadFile(file);

        LOG.info("File uploaded - " + ret);

        filesToProcess.add(UPLOAD_DESTINATION + FilenameUtils.getName(f.getName()));
        session.setAttribute("filesToProcess", filesToProcess);

  final RequestDispatcher dispatcher = request.getRequestDispatcher("Validate");
        if (null != dispatcher) {
         dispatcher.forward(request, response);
        }
    } catch (FileUploadException e) {
        LOG.info("Exception " + e.getMessage());
        e.printStackTrace();
    } catch (Exception e) {
        LOG.info("Exception " + e.getMessage());
        e.printStackTrace();
    }

我今天上午的大部分时间都在处理这个问题,但一无所获。即使我完全摆脱 Apache 公共(public)文件的东西并自己处理请求的解析,我仍然无法适本地构建数据源。

谢谢!

最佳答案

这实际上很简单,我只是将字节从 InputStream 复制到 DataSource:

FileItem f = files.get(0);

// there is a problem here where the file being created is empty, since we only have a
// partial path:
DataSource source = new FileDataSource(new File(f.getName()));

// because of the above problem, we are going to copy over the data ourselves:
byte[] sourceBytes = f.get();
OutputStream sourceOS = source.getOutputStream();
sourceOS.write(sourceBytes);

关于java - 从 InputStream 或 Byte 数组构造 DataSource,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2141829/

相关文章:

java - 在 servlet 中读取请求正文时出现问题

java - Servlet 未连接到 MySQL 或 doPost() 不起作用

java - 是否有与 Apache Commons CircularFifoBuffer 等效的 Guava?

java - 在多个 Controller 中管理多个模型以跟踪它们

java - Maven突然下载maven-clover2-plugin

java - 这里如何解决NullPointer异常错误?

android - 在 Android Studio 上导入 Apache 库

java - 将 Spring Security 添加为依赖项会导致应用程序表现不同

java - 请求 URL 中的括号合法但在 URI 中不合法(Java)?

c# - 无法弄清楚这些 C# 和 Java 代码的不同之处