在jsp中上传文件

时间:2017-08-24 14:22:11

标签: jsp file-upload

我已尝试通过c盘内文件夹中的表单上传文件。 但代码不起作用。我不知道故障在哪里,但代码没有响应意味着它没有给出错误但没有任何东西存储在我应该存储文件的文件夹中。请帮帮我,告诉我哪里有错。

<html>
    <head>
        <title>Upload File</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <%@page import="java.io.*" %>
    </head>
    <body>

        <form name="uploadForm" action="save.jsp" enctype="multipart/form-data">

           <%
               String saveFile=new String();
               String contentType=request.getContentType();

               if(contentType!=null && contentType.indexOf("multipart/form-data")>=0){

               DataInputStream in=new DataInputStream(request.getInputStream());
               int formDataLength=request.getContentLength();
               byte dataBytes[]=new byte[formDataLength]; 
               int byteRead=0;
               int totalBytesRead=0;

                    while(totalBytesRead<formDataLength){

                    byteRead=in.read(dataBytes,totalBytesRead,formDataLength);
                    totalBytesRead+=byteRead;

                    }

                 String file=new String(dataBytes);
                 saveFile =file.substring(0,saveFile.indexOf("\n"));
                 saveFile =file.substring(saveFile.lastIndexOf("\\")+1,saveFile.indexOf("\""));

                 int lastIndex =contentType.lastIndexOf("=");

                 String boundary=contentType.substring(lastIndex+1,contentType.length());

                 int pos;

                 pos=file.indexOf("filename=\"");
                 pos=file.indexOf("\n",pos)+1;
                 pos=file.indexOf("\n",pos)+1;
                 pos=file.indexOf("\n",pos)+1;

                 int bouandryLocation=file.indexOf(boundary,pos)-4;

                 int startPos=((file.substring(0,pos)).getBytes()).length;
                 int endPos=((file.substring(bouandryLocation,pos)).getBytes()).length;


                 saveFile="C:/UplaodDir/" + saveFile;


                 File ff=new File(saveFile);



                 FileOutputStream fileOut=new FileOutputStream(ff);
                 fileOut.write(dataBytes,startPos,(endPos-startPos));
                 fileOut.flush();
                 fileOut.close();

               }

           %>          

            <input type="file" name="file" width="100" />
            <input type="submit" value="submit"/>

        </form> 

    </body>
</html> 

0 个答案:

没有答案