Загрузка файла JSP AJAX - PullRequest
       1

Загрузка файла JSP AJAX

3 голосов
/ 18 апреля 2011

Я попытался загрузить файл и отобразить содержимое файла обратно в браузер с помощью ajax и jsp. Однако, мне кажется, это не очень хорошо работает.

Видимо, в JSP-странице Upload.jsp, когда я пытаюсь получитьContentType () из запроса, 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();
            }
 %>

1 Ответ

4 голосов
/ 18 апреля 2011

Попробуйте следующий код ...

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>");

Надеюсь, это поможет..

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...