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

时间:2012-02-14 00:12:01

标签: java servlets file-upload

这是我的代码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 Server的Ne​​tbeans 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.

0 个答案:

没有答案