使用jquery文件上传使用imagename上传图像

时间:2012-03-25 07:10:06

标签: java jquery ajax jsp file-upload

我正在使用AjaxFileUpload上传包含一些数据的文件(输入框)。每当我尝试上传文件时,它会显示文件上传... ,然后卡住一段时间。我检查了我的数据库,但发现它没有效果。

以下是我到目前为止所做的事情。

的index.jsp

<%@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>
        <title>Ajax File Upload</title>
        <script type="text/javascript" src="jquery.js"></script>
        <script type="text/javascript" src="ajaxfileupload.js"></script>
        <script type="text/javascript">
            $(document).ready(function(){
                $("#login_frm").submit(function(){
                    //remove previous class and add new "myinfo" class
                    // e.preventDefault();

                $("#msgbox1").removeClass().addClass('myinfo').text('Uploading .... ').fadeIn(1000);
                $.ajaxFileUpload({
                    url :'AddPhoto',
                    secureuri:false,
                    fileElementId:'image',
                    dataType: 'json',
                    success: function(msg){
                      //   alert(msg.MSG)
                        $("#msgbox1").removeClass().addClass('myinfo').text(msg.MSG).fadeIn(1000);
                        if(msg.MSG=="Image Successfully Uploaded!!")
                        {
                            document.getElementById("image").disabled="disabled";
                        }
                    }
                });

                return false;
            });

        });

    </script>
    <link href="style.css" rel="stylesheet" type="text/css" />
    <link href="login_style.css" rel="stylesheet" type="text/css" />
</head>
<body>
    <form name="login_frm" id="login_frm" action="" method="post">
        <div id="login_box">
            <div id="login_header">&nbsp;&nbsp;&nbsp;Citizen Login </div>
            <div id="form_val" style="background-color:black">
                <div class="label">Image Name :</div>
                <div class="control"><input type="text" name="imgname" id="imgname"/></div>
                <div style="clear:both;height:0px;"></div>
                <div id="msgbox"></div>
                <div class="label">Photograph :</div>
                <div class="control"><input type="file" name="image" id="image"/></div>
                <div style="clear:both;height:0px;"></div>
                <div id="msgbox1"></div>
            </div>
            <div id="login_footer">
                <label>
                    <input type="submit" name="upload" id="upload" value="Upload" class="send_button" />
                </label>
            </div>
        </div>
    </form>
</body>

AddPhoto.java

package fileupload;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
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;

public class AddPhoto extends HttpServlet {

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            // Apache Commons-Fileupload library classes
            DiskFileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload sfu = new ServletFileUpload(factory);

            if (!ServletFileUpload.isMultipartContent(request)) {
                out.print("{MSG:'File Not Uploaded !!'}");
                return;
            } else {
                // parse request
               out.print("{MSG:'File Uploading....'}");
               List items = sfu.parseRequest(request);             
                FileItem file = (FileItem) items.get(0);
                String type = file.getContentType();
                int size = (int) (file.getSize() / 1024);
                //String name="images";
                String name = file.getFieldName();
                 out.println("{MSG:'Error" +size+ "'}");
                if (name.equals("image")) {
                    if ((type.equals("image/jpeg")) && ((size < 201) && (size > 10))) {
                        Class.forName("oracle.jdbc.driver.OracleDriver");
                        Connection con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "epolicia", "admin");
                        con.setAutoCommit(false);
                        PreparedStatement ps = con.prepareStatement("insert into images(image) values(?)");
                        ps.setBinaryStream(1, file.getInputStream(), (int) file.getSize());
                        ps.executeUpdate();
                        con.commit();
                        con.close();
                        out.println("{MSG:'ID Proof Successfully Uploaded !!'}");

                    } else {
                        out.print("{MSG:'ID Proof is not jpg or its more than 200kb!!'}");
                    }
                } else {
                    out.print("{MSG:'File Not Uploaded !!'}");
                }
            }
        } catch (Exception ex) {
            out.println("{MSG:'Error" + ex.getMessage() + "'}");
        }
    }
}

1 个答案:

答案 0 :(得分:0)

关于你的问题,我有2分:

  1. 检查那里:Asynchronous file upload (AJAX file upload) using jsp and javascript。 如果使用JSP,Ajax File uploader是不错的选择。阅读该主题。

  2. 建议:不要使用

  3. if(msg.MSG=="Image Successfully Uploaded!!")

    比较结果。试试吧

    if(msg.MSG === 1) { // or msg.MSG === true
       //process and show the successfully uploaded string 
     }
    

    这就是全部。我希望这些可以帮到你。