使用 Java Servlet 和 Apache Commons Library 上传文件或图像

发布于 2025-01-04 20:44:31 字数 6688 浏览 0 评论 0原文

这是我的代码 index.jsp

<%-- 
    Document   : index
    Created on : 14 Feb, 2012, 4:46:05 AM
    Author     : Sanjib Narzary
--%>

<%@page contentType="text/html" 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>JSP Page</title>
    </head>
    <body>
        <form action="/CBKD_WEB/img" method="post"
              enctype="multipart/form-data"
              name="productForm" id="productForm"><br><br>
            <table width="400px" align="center" border=0
                   style="background-color:ffeeff;">
                <tr>
                    <td align="center" colspan=2 style=" font-weight:bold;font-size:20pt;">
                        Image Details
                    </td>
                </tr>

                <tr>
                    <td align="center" colspan=2>&nbsp;</td>
                </tr>

                <tr>
                    <td>Image Link: </td>
                    <td>
                        <input type="file" name="file" id="file">
                    <td>
                </tr>

                <tr>
                    <td></td>
                    <td><input type="submit" name="Submit" value="Submit"></td>
                </tr>
                <tr>
                    <td colspan="2">&nbsp;</td>
                </tr>

            </table>
        </form>
    </body>
</html>

和 Servlet img.java

import java.io.*;
import java.sql.*;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.*;


import javax.servlet.*;
import javax.servlet.http.*;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
//import org.apache.commons.fileupload.*;
public class img extends HttpServlet {

    @Override
    public void doPost(HttpServletRequest request,
            HttpServletResponse response)
            throws ServletException, IOException {
        PrintWriter out = response.getWriter();
        boolean isMultipart = ServletFileUpload.isMultipartContent(
                request);
        System.out.println("request: " + request);
        if (!isMultipart) {
            System.out.println("File Not Uploaded");
        } else {
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            List items = null;


            try {
                items = upload.parseRequest(request);
            } catch (FileUploadException ex) {
                Logger.getLogger(img.class.getName()).log(Level.SEVERE, null, ex);
            }
            System.out.println("items: " + items);

            Iterator itr = items.iterator();
            while (itr.hasNext()) {
                FileItem item = (FileItem) itr.next();
                if (item.isFormField()) {
                    String name = item.getFieldName();
                    System.out.println("name: " + name);
                    String value = item.getString();
                    System.out.println("value: " + value);
                } else {
                    try {
                        String itemName = item.getName();
                        Random generator = new Random();
                        int r = Math.abs(generator.nextInt());

                        String reg = "[.*]";
                        String replacingtext = "";
                        System.out.println("Text before replacing is:-"
                                + itemName);
                        Pattern pattern = Pattern.compile(reg);
                        Matcher matcher = pattern.matcher(itemName);
                        StringBuffer buffer = new StringBuffer();

                        while (matcher.find()) {
                            matcher.appendReplacement(buffer, replacingtext);
                        }
                        int IndexOf = itemName.indexOf(".");
                        String domainName = itemName.substring(IndexOf);
                        System.out.println("domainName: " + domainName);

                        String finalimage = buffer.toString() + "_" + r + domainName;
                        System.out.println("Final Image===" + finalimage);

                        File savedFile = new File("E:/sanjib/" + "temp/" + finalimage);
                        item.write(savedFile);
                        out.println("<html>");
                        out.println("<body>");
                        out.println("<table><tr><td>");
                        out.println("<img src=images/" + finalimage + ">");
                        out.println("</td></tr></table>");


                            out.println("</body>");
                            out.println("</html>");

                    } catch (Exception e) {
                    }
                }
            }
        }
    }
}

这段代码很好,在带有 Glassfish 3.1 服务器的 Netbeans Web 应用程序中没有任何错误。但我的问题是,如果我尝试上传图像,它会在 Firefox 中显示警报,例如页面加载时与服务器的连接已重置,而在 Google Chrome 中则显示此错误

This web page is not available
The connection to localhost was interrupted.
Here are some suggestions:
Reload this web page later.
Check your Internet connection. Reboot any routers, modems or other network devices that you may be using.
Add Google Chrome as a permitted programme in your firewall or antivirus software's settings. If it is already a permitted programme, try deleting it from the list of permitted programmes and adding it again.
If you use a proxy server, check your proxy settings or contact your network administrator to make sure that the proxy server is working. If you don't believe you should be using a proxy server, adjust your proxy settings: Go to the spanner menu > Options > Under the Bonnet > Change proxy settings... > LAN Settings and deselect the "Use a proxy server for your LAN" checkbox.
Error 101 (net::ERR_CONNECTION_RESET): The connection was reset.

Here is my Code index.jsp

<%-- 
    Document   : index
    Created on : 14 Feb, 2012, 4:46:05 AM
    Author     : Sanjib Narzary
--%>

<%@page contentType="text/html" 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>JSP Page</title>
    </head>
    <body>
        <form action="/CBKD_WEB/img" method="post"
              enctype="multipart/form-data"
              name="productForm" id="productForm"><br><br>
            <table width="400px" align="center" border=0
                   style="background-color:ffeeff;">
                <tr>
                    <td align="center" colspan=2 style=" font-weight:bold;font-size:20pt;">
                        Image Details
                    </td>
                </tr>

                <tr>
                    <td align="center" colspan=2> </td>
                </tr>

                <tr>
                    <td>Image Link: </td>
                    <td>
                        <input type="file" name="file" id="file">
                    <td>
                </tr>

                <tr>
                    <td></td>
                    <td><input type="submit" name="Submit" value="Submit"></td>
                </tr>
                <tr>
                    <td colspan="2"> </td>
                </tr>

            </table>
        </form>
    </body>
</html>

and Servlet img.java

import java.io.*;
import java.sql.*;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.*;


import javax.servlet.*;
import javax.servlet.http.*;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
//import org.apache.commons.fileupload.*;
public class img extends HttpServlet {

    @Override
    public void doPost(HttpServletRequest request,
            HttpServletResponse response)
            throws ServletException, IOException {
        PrintWriter out = response.getWriter();
        boolean isMultipart = ServletFileUpload.isMultipartContent(
                request);
        System.out.println("request: " + request);
        if (!isMultipart) {
            System.out.println("File Not Uploaded");
        } else {
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            List items = null;


            try {
                items = upload.parseRequest(request);
            } catch (FileUploadException ex) {
                Logger.getLogger(img.class.getName()).log(Level.SEVERE, null, ex);
            }
            System.out.println("items: " + items);

            Iterator itr = items.iterator();
            while (itr.hasNext()) {
                FileItem item = (FileItem) itr.next();
                if (item.isFormField()) {
                    String name = item.getFieldName();
                    System.out.println("name: " + name);
                    String value = item.getString();
                    System.out.println("value: " + value);
                } else {
                    try {
                        String itemName = item.getName();
                        Random generator = new Random();
                        int r = Math.abs(generator.nextInt());

                        String reg = "[.*]";
                        String replacingtext = "";
                        System.out.println("Text before replacing is:-"
                                + itemName);
                        Pattern pattern = Pattern.compile(reg);
                        Matcher matcher = pattern.matcher(itemName);
                        StringBuffer buffer = new StringBuffer();

                        while (matcher.find()) {
                            matcher.appendReplacement(buffer, replacingtext);
                        }
                        int IndexOf = itemName.indexOf(".");
                        String domainName = itemName.substring(IndexOf);
                        System.out.println("domainName: " + domainName);

                        String finalimage = buffer.toString() + "_" + r + domainName;
                        System.out.println("Final Image===" + finalimage);

                        File savedFile = new File("E:/sanjib/" + "temp/" + finalimage);
                        item.write(savedFile);
                        out.println("<html>");
                        out.println("<body>");
                        out.println("<table><tr><td>");
                        out.println("<img src=images/" + finalimage + ">");
                        out.println("</td></tr></table>");


                            out.println("</body>");
                            out.println("</html>");

                    } catch (Exception e) {
                    }
                }
            }
        }
    }
}

This code is fine and working without any error in Netbeans Web Application with Glassfish 3.1 Server. But what my problem is if i try to upload the image it is showing Alert in Firefox like The connection to the server was reset while the page was loading and in Google Chrome This Error

This web page is not available
The connection to localhost was interrupted.
Here are some suggestions:
Reload this web page later.
Check your Internet connection. Reboot any routers, modems or other network devices that you may be using.
Add Google Chrome as a permitted programme in your firewall or antivirus software's settings. If it is already a permitted programme, try deleting it from the list of permitted programmes and adding it again.
If you use a proxy server, check your proxy settings or contact your network administrator to make sure that the proxy server is working. If you don't believe you should be using a proxy server, adjust your proxy settings: Go to the spanner menu > Options > Under the Bonnet > Change proxy settings... > LAN Settings and deselect the "Use a proxy server for your LAN" checkbox.
Error 101 (net::ERR_CONNECTION_RESET): The connection was reset.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文