java - JSP AJAX文件上传

标签 java ajax jsp web-applications

我尝试使用 ajax 和 jsp 上传文件并将文件内容显示回浏览器。但是,它似乎对我来说效果不是很好。

显然,在 JSP 页面 Upload.jsp 中,当我尝试从请求中获取 getContentType() 时,request.getcontentType() == null

有没有人有这方面的经验?非常感谢。

表单

<form id="uploadform" name="uploadform" enctype="multipart/form-data" action="Upload.jsp" method="post">
     <input type="file" name="file" id="listfile" onChange="upload(this.value)"/>
</form>

这是 Javascript 函数上传(ifile)

function upload(ifile){
                if (window.XMLHttpRequest){
                    //IE7 + and other browsers
                    xmlhttp = new XMLHttpRequest();
                }else{
                    //IE 6, 5
                    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
                }

                if(xmlhttp == null){
                    alert("File Uploading is not available because your browser does not support AJAX");
                    return;
                }

                //Function to process response form upload.jsp
                xmlhttp.onreadystatechange = function(){
                    if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
                        var response = xmlhttp.responseText;

                        alert(response);
                    }
                }

                xmlhttp.open("POST", "Upload.jsp?file="+ifile, true);
                xmlhttp.send(null);
            }

这是JSP页面Upload.jsp

<%@page import="java.util.StringTokenizer"%>
<%@page import="java.io.*" %>

<%

        response.setContentType("text/html");
        response.setHeader("Cache-control", "no-cache");

    String contentType = request.getContentType();

    if ((contentType != null) && (contentType.indexOf("multipart/form-data") >= 0)) {
        DataInputStream in = new DataInputStream(request.getInputStream());
        //get length of Content type data
        int formDataLength = request.getContentLength();
        byte dataBytes[] = new byte[formDataLength];
        int byteRead = 0;
        int totalBytesRead = 0;
        //convert the uploaded file into byte code
        while (totalBytesRead < formDataLength) {
            byteRead = in.read(dataBytes, totalBytesRead,formDataLength);
            totalBytesRead += byteRead;
        }

                //decode byte array using default charset
        String file = new String(dataBytes);

                //Using StringTokenizer to extract genes list
                StringTokenizer st = new StringTokenizer(file, " ");

                int numtoken = st.countTokens();

                for(int i = 0; i < numtoken-1; i++){
                    st.nextToken();
                    }

                String a = st.nextToken();

                st = new StringTokenizer(a, " \n");
                numtoken = st.countTokens();


                String postlink = "";

                st.nextToken();
                st.nextToken();

                for(int i = 1; i < numtoken-3; i++){
                    String temp = st.nextToken();
                    char[] c = temp.toCharArray();
                    temp = new String(c, 0, c.length-1);
                    if(!" ".equalsIgnoreCase(temp)){
                        postlink = postlink + temp + ",";
                    }
                }

                String temp = st.nextToken();
                postlink = postlink + temp;

                out.println(postlink);
                out.flush();
                out.close();

         }else if (contentType == null){
            out.println("Not a valid file");
            out.flush();
            }
 %>

最佳答案

试试下面的代码...

HTML:

<form id="uploadform" name="uploadform" enctype="multipart/form-data" action="Upload.jsp" method="post">
         <input type="file" name="file" id="listfile" onChange="upload()"/>
    </form>

<iframe id="target-iframe" name="target-iframe">
<div id="status">Uploading....</div>

Javascript:

function upload(){
document.getElementById('uploadform').target = 'target_iframe';
document.getElementById('status').style.display="block";
document.getElementById("uploadform").submit();
}

上面的 Javascript 代码会将提交重定向到 iframe(隐藏)而不是主页本身

JSP:

///do the proccessing in the JSP and in the end output your file content on the some message like follows....
     out.println("<script type='text/javascript'>");
     out.println("parent.document.getElementById('status').innerHTML=\"<center>SUCCESSFULLY UPLOADED</center>\"; alert('SUCCESSFULLY UPLOADED')");
     out.println("</script>");

希望这有助于...

关于java - JSP AJAX文件上传,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5700172/

相关文章:

java - 为什么 BigDecimal 自然排序与 equals 不一致?

java - 使用 Amazon SWF 限制下游服务的 TPS

ajax - 创建 'Ajaxified' 表单字段类型

javascript - 提交链接,无需刷新,无需ajax

java - 引用HTML文件中的servlet以获取Tomcat中的.war文件

java - 为什么我的正则表达式在 Java 中不起作用

java - 使用 jar 文件和资源创​​建 exe

php - Service unavailable 服务暂时不可用错误

java - 使用Java Server Pages,提交后如何制作 "register"表单数据

不检索整个结果集的 JSP 分页?