`
dyllove98
  • 浏览: 1384253 次
  • 性别: Icon_minigender_1
  • 来自: 济南
博客专栏
73a48ce3-d397-3b94-9f5d-49eb2ab017ab
Eclipse Rcp/R...
浏览量:38381
4322ac12-0ba9-3ac3-a3cf-b2f587fdfd3f
项目管理checkList...
浏览量:78746
4fb6ad91-52a6-307a-9e4f-816b4a7ce416
哲理故事与管理之道
浏览量:131918
社区版块
存档分类
最新评论

纯servlet文件上传

 
阅读更多

对于学习JSP/SERVLET的人来说,学会使用jar包实现文件上传的只是一种入门,就好像别人写了一个类,你知道调用类的main方法一样。但是,我们不仅要知道怎么调用main方法,更要知道main方法中写的是什么。最近对文件上传下载感兴趣,就找了找相关资料,结合自己所学,做了一个文件上传的例子。便于大家的学习。

 例子的功能:

  1. 实现多文件上传下载
  2. 实现获取提交的form表单的其他项
  3. 实现获取上传文件的列表
  4. 注意:本例子在struts下失效,原因是struts对request进行过封装。

文件只有两个。

1.test.jsp

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>首页</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

</head>
<body>
    <form action="FileUpload" method="post"
        enctype="multipart/form-data">
        <table>
            <tr>
                <td width="120" align="center">值1:</td>
                <td width="180"><input type="text" name="name1" ></td>
            </tr>
            <tr>
                <td width="120" align="center">值2:</td>
                <td width="180"><input type="text" name="name2" ></td>
            </tr>
            <tr>
                <td width="120" align="center">路径1:</td>
                <td width="180"><input type="file" name="file"></td>
            </tr>
            <tr>
                <td width="120" align="center">路径2:</td>
                <td width="180"><input type="file" name="file2"></td>
            </tr>
            <tr>
                <td><input type="submit" value="确定" /></td>
            </tr>
        </table>
    </form>
</body>
</html>

 

   

2.FileUpload.java

import java.io.BufferedOutputStream;

/**
 * 上传附件
 */
@WebServlet("/FileUpload")
public class FileUpload extends HttpServlet {
    private String fpath="c:/";
    private Map<String, String> map=new HashMap<String, String>();
    private List<File> files=new ArrayList<File>();
    
    private long getFileUpload(HttpServletRequest request) throws IOException{
        long start=System.currentTimeMillis();
        ServletInputStream in = request.getInputStream();
        
        getFileUpload(in,getSign(request),fpath);
        long end=System.currentTimeMillis();
        return end-start;
    }
    
    public String getSign(HttpServletRequest request){
        String contentType = request.getContentType();
        int index = contentType.indexOf( "boundary=" );
        return  "--" + contentType.substring( index + 9 );
    }

    private void getFileUpload(ServletInputStream in,String sign, String fpath) throws IOException {
        int l=0;
        byte[] b=new byte[1024];
        //用来指示要上传的文件
        File file=null;;
        BufferedOutputStream out=null;
        //用来存放form表单中的value的值。这儿考虑到textarea等,所以用到了sb
        StringBuilder sb=new StringBuilder();
        //用来存放form中的name值
        String name="";
        while((l=in.readLine(b, 0, b.length))>0){
            if (file==null) {
                String temp=new String(b,0,l);
                String lowerTemp=temp.toLowerCase();
                if (lowerTemp.startsWith( "content-disposition: form-data; " )) {
                    if (lowerTemp.contains("filename=\"") && !lowerTemp.contains("filename=\"\"")) {
                        int nIndex=lowerTemp.indexOf("filename=\"");
                        int nLastIndex=temp.indexOf("\"",nIndex+10);
                        String filePath=temp.substring(nIndex+10, nLastIndex);
                        String filename=filePath.substring(filePath.lastIndexOf("\\")+1);
                        file=new File(fpath+filename);
                        out=new BufferedOutputStream(new FileOutputStream(file));
                        in.readLine(b, 0, b.length);
                    }else if (lowerTemp.contains("name=\"")) {
                        name=temp.substring(lowerTemp.indexOf("name=\"")+6,temp.lastIndexOf("\""));
                    }
                    in.readLine(b, 0, b.length);
                }else if (!"".equals(name)){
                    if (temp.startsWith(sign)) {
                        map.put(name, sb.toString());
                        name="";
                        sb=new StringBuilder();
                    }else
                        sb.append(new String(b,0,l-2));
                }
                continue;
            }
            
            if (l==sign.length()+2 || l==sign.length()+4) {
                String temp=new String(b,0,l);
                if (temp.startsWith(sign)) {
                    out.flush();
                    out.close();
                    files.add(new File(file.getAbsolutePath()));
                    file=null;
                    out=null;
                    continue;
                }
            }
            out.write(b,0,l);
            out.flush();
        }
        if (file!=null) {
            files.add(new File(file.getAbsolutePath()));
        }
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("GBK");
        long time=getFileUpload(request);
        System.out.println("上传文件花费时间为:"+time+"毫秒,文件上传位置为:"+fpath);
        System.out.println("form表单的值为:");
        for (String key : map.keySet()) {
            System.out.println(key+":"+map.get(key));
        }
        System.out.println();
        System.out.println("上传的文件有:");
        for(File file:files){
            System.out.println(file.getName());
        }
        
        response.getWriter().write("success!!!");
    }

}

 

   

3.附送一个ServletInputStream读取的内容:

Content-Disposition: form-data; name="name1"

   

1

------WebKitFormBoundaryXjfYhqOTqQagpQHN

Content-Disposition: form-data; name="name2"

   

2

------WebKitFormBoundaryXjfYhqOTqQagpQHN

Content-Disposition: form-data; name="file"; filename="a.txt"

Content-Type: text/plain

   

 

 

 

------WebKitFormBoundaryXjfYhqOTqQagpQHN

Content-Disposition: form-data; name="file2"; filename="b.txt"

Content-Type: text/plain

   

1

2

3

------WebKitFormBoundaryXjfYhqOTqQagpQHN--

  

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics