2009年4月14日星期二

实现文件上传的Servlet

今天帮同学实现一个上传的servlet,本来以为很简单,最后做起来,才发现还是比较复杂的,虽然现在已经用惯了spring,但是基本的servlet也不能忘记。今天做这个收获颇多,特贴出来,以便以后使用。其实写的不是优雅,但也基本能完成任务。
对于文件上传有这么几点,首先是servlet接受到文件上传表单的数据后,并未提取出文件名等信息,需要自己分析。而且在文件数据前后都有一个添加上去的头和尾信息,需要自己去除。下面是我的代码:

import java.io.DataInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class HandleFileServlet extends HttpServlet {
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        String path = "D:\\";
        String filename = "";

        // System.out.println(getServletContext().getContextPath());
        System.out.println("content type:" + request.getContentType());
        System.out.println("file length:" + request.getContentLength());

        ServletInputStream is = request.getInputStream();
        int readLen = 0, conLen = request.getContentLength();
        byte[] b = new byte[1024];
        int len = 0;
        String terminator = "";
        // read the head infomation
        while ((len = is.readLine(b, 0, b.length)) != -1) {
            readLen += len;
            String str = new String(b,0,len);
            System.out.println("a line: " + "length:" + len + "data:" + str);
            int pos = -1;
            //got terminate string
            if (str.startsWith("---------------------------")) {
                terminator = str;
                terminator += "--";
                System.out.println(terminator);
            }
            //got filename
            if ((pos = str.indexOf("filename=\"")) != -1) {
                pos += "filename=\"".length();
                filename = str.substring(pos, str.lastIndexOf("\""));
                System.out.println("got filename:" + filename);
            }
            // quit read head data
            if (b[0] == '\r' && b[1] == '\n') {
                System.out.println("break from rn");
                break;
            }
        }
        if (filename.length() == 0)
            filename = "unknown_name.txt";
        File f = new File(path, filename);
        if (!f.createNewFile()) {
            System.out.println("Cannot create file");
        }
        FileOutputStream fos = new FileOutputStream(f);
        byte[] data = new byte[2048];
        int toReadLen = data.length;
        
        System.out.println("read length:"+readLen);
        System.out.println("content length:"+ conLen);
        System.out.println("conLen - terminator.length() " + (conLen - terminator.length()));
        
        if(readLen + data.length > ( conLen - terminator.length()))
        {
            toReadLen = conLen - terminator.length() - readLen-2;
        }
        while ((len = is.read(data, 0,toReadLen))!= 0 ) {
            readLen += len;
            //String tempStr = new String(data, 0, len);
            fos.write(data, 0, len);
            if(readLen + data.length > ( conLen - terminator.length()))
            {
                toReadLen = conLen - terminator.length() - readLen-2;
            }
        }
        fos.close();
        System.out.println("read after header:" + new String(data));

    }
}

html页面:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>文件上传测试</title>
</head>
<body>
<h1>选择一个文本文件上传:</h1>
<form action="servlet/upload" method="post"
            enctype="multipart/form-data">
            <input type="file" name="file" id="file1" />
             <input type="submit" value="上传" />
        </form>
</body>
</html>

--
Be yourself.

0 评论: