JSP AJAX 文件上传

3
我尝试使用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函数upload(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();
            }
 %>

你是想在不刷新屏幕的情况下上传文件吗?这样是不可能的...请搜索并查找ajax支持的内容类型。 - Sangeet Menon
嗨。我明白了,所以Ajax不支持文件内容类型。你建议我如何解决这个问题?我想要做的是上传一个文件并在不刷新浏览器的情况下将其打印回一个字段中。谢谢。 - Scicare
尝试使用我下面发布的答案,如果您有任何疑问,请问我。 - Sangeet Menon
1个回答

4
尝试以下代码... 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>");

希望这能有所帮助...

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接