java - 由servlet处理的多部分图像上传post请求

标签 java servlets servlet-filters

我必须使用 servlet 在服务器上上传图像,并且对 servlet 的请求正在通过 post 方法。 post请求的代码如下:

public class PostImageRequest {
public static void main(String[] args) throws Exception {

    final String exsistingFileName = "E:\\Users\\snikhil\\Downloads\\qwe.jpg";
    File binaryFile = new File(exsistingFileName);
    String param = "value";
    DataInputStream inStream = null;
    String boundary = Long.toHexString(System.currentTimeMillis()); // JustRandomValue

    String CRLF = "\r\n"; // Line separator required by multipart/form-data.
    String charset = "UTF-8";
    String urlString = "http://localhost:89/ImageUploaderv3/ImageUploadServlet";

    URLConnection connection = new URL(urlString).openConnection();
    connection.setDoOutput(true);// it is to indicate post method call
    connection.setRequestProperty("Content-Type",
            "multipart/form-data; boundary=" + boundary);
    PrintWriter writer = null;

    try {
        OutputStream output = connection.getOutputStream();
        writer = new PrintWriter(new OutputStreamWriter(output, charset),
                true); // true = autoFlush, important!

        // Send normal param.
        writer.append("--" + boundary).append(CRLF);
        writer.append("Content-Disposition: form-data; name=\"param\"")
                .append(CRLF);
        writer.append("Content-Type: text/plain; charset=" + charset)
                .append(CRLF);
        writer.append(CRLF);
        writer.append(param).append(CRLF).flush();

        // Send binary file.
        writer.append("--" + boundary).append(CRLF);
        writer.append(
                "Content-Disposition: form-data; name=\"binaryFile\"; filename=\""
                        + binaryFile.getName() + "\"").append(CRLF);
        writer.append(
                "Content-Type: "
                        + URLConnection.guessContentTypeFromName(binaryFile
                                .getName())).append(CRLF);
        writer.append("Content-Transfer-Encoding: binary").append(CRLF);
        writer.append(CRLF).flush();
        InputStream input = null;
        try {
            input = new FileInputStream(binaryFile);
            byte[] buffer = new byte[1024];
            for (int length = 0; (length = input.read(buffer)) > 0;) {
                output.write(buffer, 0, length);
            }
            output.flush(); // Important! Output cannot be closed. Close of
                            // writer will close output as well.
        } finally {
            if (input != null)
                try {
                    input.close();
                } catch (IOException logOrIgnore) {
                }
        }
        writer.append(CRLF).flush(); // CRLF is important! It indicates end
                                        // of binary boundary.
        // End of multipart/form-data.
        writer.append("--" + boundary + "--").append(CRLF);
    } finally {
        if (writer != null)
            writer.close();
    }
    // ------------------ read the SERVER RESPONSE

    try {
        inStream = new DataInputStream(connection.getInputStream());
        String str;
        while ((str = inStream.readLine()) != null) {
            System.out.println("Server response is: " + str);
            System.out.println("");
        }
        inStream.close();

    } catch (IOException ioex) {
        System.out.println("From (ServerResponse): " + ioex);

    }

}

}

现在我正在尝试使用 commons-fileupload-1.2.2 和 commons-io-2.4 jar 在服务器上上传图像,但我不知道如何处理该请求。在这种情况下如何使用 FileItem 的迭代器? servlet部分的代码如下。

class ImageUploadServlet extends HttpServlet {

private boolean isMultipart;
private String filePath;
private int maxFileSize = 50 * 1024;
private int maxMemSize = 4 * 1024;
private File file;
private String realpath;

public void init() {
    // Get the file location where it would be stored.
    filePath = getServletContext().getInitParameter("file-upload");
    String h;
    h = getInitParameter("realpath");
    if (h != null) {
        realpath = h;
    }
    realpath = getServletConfig().getServletContext().getRealPath(realpath) + "/";
    System.err.println("realparh is  is =" + realpath);
}

//call post method 
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, java.io.IOException {

    isMultipart = ServletFileUpload.isMultipartContent(request);
    isMultipart = ServletFileUpload.isMultipartContent(request);
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    if (!isMultipart) {
        out.println("<html>");
        out.println("<head>");
        out.println("<title>Servlet upload</title>");
        out.println("</head>");
        out.println("<body>");
        out.println("<p>No file uploaded</p>");
        out.println("</body>");
        out.println("</html>");
        return;
    }

    DiskFileItemFactory factory = new DiskFileItemFactory();
    // maximum size that will be stored in memory
    factory.setSizeThreshold(maxMemSize);
    // Location to save data that is larger than maxMemSize.
    factory.setRepository(new File("F:\\Servers\\temp"));

    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);
    // maximum file size to be uploaded.
    upload.setSizeMax(maxFileSize);

    try {
        List<FileItem> fileItems = upload.parseRequest(request);
        ///how to process request here ...
        ///Image file send .....



    } catch (Exception ex) {
        System.out.println(ex);
    }



}

}

请帮助如何填写代码来处理请求,如果我可以通过其他方式做到这一点,请帮助我。

最佳答案

就是这样:

// Process the uploaded items

Iterator iter = items.iterator();

while (iter.hasNext()) {

  FileItem item = (FileItem) iter.next();

  if (item.isFormField()) {

    processFormField(item);
  } else {

    processUploadedFile(item);
  }
}

参见:

关于java - 由servlet处理的多部分图像上传post请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11772142/

相关文章:

java - 经过Java Filter后用RequestDispatcher转发

JavaFX - 多维 HashMap 被覆盖

java - 我第一次尝试玩 Java 游戏时,在读取图像时以 7 fps 结束?

java - 带有 Tomcat 的 JSR-356 WebSockets - 如何限制单个 IP 地址内的连接?

java - Tomcat 拒绝访问域上的共享目录

java - 我如何在 Tomcat Servlet 中打印一些东西, hibernate 3 秒然后转发到另一个 servlet?

java - Http Servlet 请求在读取一次后会丢失 POST 正文中的参数

java - Android 排序位置列表 - java.lang.IllegalArgumentException : Comparison method violates its general contract

java - 类路径和可移植性

java - Web 框架应该是 Filter 还是 Servlet?