【问题标题】:how to process file from a java process uploaded using servlets如何处理使用 servlet 上传的 java 进程中的文件
【发布时间】:2016-01-07 04:56:10
【问题描述】:

我开发了一个 Java servlet (tomcat 6.0) 来处理从客户端上传到服务器的文件。到目前为止,我的 javaapp 现在所能做的就是上传文件。我编写了另一个 java 应用程序,它扫描文件(excel 文档,apachi POI),并从中解析特定信息,然后打印出信息。

目标基本上是使用上传的文件,然后调用java程序处理文件。然后将数据从 java 控制台(结果)吐出到 HTML 页面。

这是我的 servlet 代码。我按照this 教程制作了这个。

小服务程序:

package net.codejava.upload;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 * A Java servlet that handles file upload from client.
 * @author www.codejava.net
 */
public class UploadServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    private static final String UPLOAD_DIRECTORY = "upload";
    private static final int THRESHOLD_SIZE     = 1024 * 1024 * 3;  // 3MB
    private static final int MAX_FILE_SIZE      = 1024 * 1024 * 40; // 40MB
    private static final int MAX_REQUEST_SIZE   = 1024 * 1024 * 50; // 50MB

    /**
     * handles file upload via HTTP POST method
     */
    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        // checks if the request actually contains upload file
        if (!ServletFileUpload.isMultipartContent(request)) {
            PrintWriter writer = response.getWriter();
            writer.println("Request does not contain upload data");
            writer.flush();
            return;
        }

        // configures upload settings
        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setSizeThreshold(THRESHOLD_SIZE);
        factory.setRepository(new File(System.getProperty("java.io.tmpdir")));

        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setFileSizeMax(MAX_FILE_SIZE);
        upload.setSizeMax(MAX_REQUEST_SIZE);

        // constructs the directory path to store upload file
        String uploadPath = getServletContext().getRealPath("")
            + File.separator + UPLOAD_DIRECTORY;
        // creates the directory if it does not exist
        File uploadDir = new File(uploadPath);
        if (!uploadDir.exists()) {
            uploadDir.mkdir();
        }

        try {
            // parses the request's content to extract file data
            List formItems = upload.parseRequest(request);
            Iterator iter = formItems.iterator();

            // iterates over form's fields
            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();
                // processes only fields that are not form fields
                if (!item.isFormField()) {
                    String fileName = new File(item.getName()).getName();
                    String filePath = uploadPath + File.separator + fileName;
                    File storeFile = new File(filePath);

                    // saves the file on disk
                    item.write(storeFile);
                }
            }
            request.setAttribute("message", "Upload has been done successfully!");
        } catch (Exception ex) {
            request.setAttribute("message", "There was an error: " + ex.getMessage());
        }
        getServletContext().getRequestDispatcher("/message.jsp").forward(request, response);
    }
}

Web XML 文件:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
        http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    id="WebApp_ID" version="2.5">
  <display-name>UploadServletApp</display-name>

  <servlet>
    <description></description>
    <display-name>UploadServlet</display-name>
    <servlet-name>UploadServlet</servlet-name>
    <servlet-class>net.codejava.upload.UploadServlet</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>UploadServlet</servlet-name>
    <url-pattern>/UploadServlet</url-pattern>
  </servlet-mapping>
</web-app>

我的上传JSP页面:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
    "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>File Upload</title>
</head>
<body>
    <center>
        <form method="post" action="UploadServlet" enctype="multipart/form-data">
            Select file to upload: <input type="file" name="uploadFile" />
            <br/><br/>
            <input type="submit" value="Upload" />
        </form>
    </center>
</body>
</html>

我的消息jsp页面:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
    "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Upload</title>
</head>
<body>
    <center>
        <h2>${requestScope.message}</h2>
    </center>
</body>
</html>

有人可以告诉我现在要做什么,如何调用我制作的单独的java程序(代码未在此处发布)来处理文件,然后让它从java控制台吐出数据(结果) 到“消息”HTML jsp 页面?我到处找,找不到解决这个问题的方法。这让我疯狂。

【问题讨论】:

  • 你有什么办法与这个其他java程序通信?它有什么作用?你能在命令行下运行它来处理这个文件吗?
  • 所以基本上我写的另一个程序实际上只是一类代码。它可以读取一个excel文档并从中解析信息,然后打印出来。我在这里发布的这个程序基本上是一个网络应用程序。我想要做的是能够在线上传文档,在我的解析信息的 java 程序中运行它,然后在我创建的 html 页面上打印结果。我真的不明白如何从服务器获取上传的文档,然后将其发送到我的 java 程序运行它。另外,我是java的菜鸟。我对这门语言还是很陌生。
  • 不是将文件存储在临时位置,而是将其存储在特定位置,然后从该物理位置获取文件进行处理。
  • 好吧,@SanjayPatel 的问题是我什至不知道如何开始寻找文件。在用户点击提交按钮并上传文件后......然后呢?我什至不知道如何继续代码。我只是迷路了。
  • 你的其他程序在上传到服务器后处理文件?

标签: java eclipse jsp tomcat servlets


【解决方案1】:

首先,您需要创建一个返回 String 并将 String 作为参数的方法。

public String getContent(String filePath) {
    // logic goes here
}

你已经为里面创建了一个类,你需要创建这个方法。 然后你需要更改 servlet 的某些部分:

doPost方法中声明一个变量String fileName = "";并改变

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

if (!item.isFormField()) {
    fileName = new File(item.getName()).getName(); // remove String 

在while循环之后调用你的类(假设FilterData是你的类名)

while (iter.hasNext()) {
    // Code
}
FilterData fd = new FilterData();
String data = fd.getData(uploadPath + "//" + fileName);
request.setAttribute("message", data);          

并删除

request.setAttribute("message", "Upload has been done successfully!");

希望对你有帮助!!!

【讨论】:

    【解决方案2】:

    如果您编写了其他 java 代码,只需在项目中包含该类:实例化该类并将其传递给文件。在您将文件写入磁盘的 servlet 中

      // saves the file on disk
      item.write(storeFile);
    

    您可以实例化您的类并将文件对象或文件路径传递给它。

    【讨论】:

    • 感谢您的回复,但我仍然不知道如何真正开始。就像我上面评论的那样,一旦用户提交文档并上传它,这将如何工作?我真的不知道如何开始这部分代码。
    猜你喜欢
    • 2010-10-30
    • 2013-11-17
    • 2020-10-17
    • 2010-10-31
    • 1970-01-01
    • 2014-03-23
    • 1970-01-01
    • 2011-06-04
    • 2017-11-20
    相关资源
    最近更新 更多