实现文件上传

首先到引入两个jar包,分别是

commons-fileupload-1.3.1.jar
commons-io-2.4.jar

index.jsp

<form action="<%=path %>/test.jsp" method="post" enctype="multipart/form-data">
  <p>文件名:<input type="text" name="username"></p>
 <p> 选择图片:<input type="file" name="nfile"></p>
 <p><input type="submit" value="提交"></p>
  </form>

 

test.jsp

复制代码
<%
request.setCharacterEncoding("utf-8");
 boolean flag =ServletFileUpload.isMultipartContent(request);
if(flag){
    DiskFileItemFactory factory =new DiskFileItemFactory();
    ServletFileUpload upload =new ServletFileUpload(factory);
    List<FileItem> filelist =upload.parseRequest(request);
    Iterator<FileItem> myitor =filelist.iterator();
    while(myitor.hasNext()){
        FileItem item =myitor.next();
        if(item!=null){
            if(item.isFormField()){
                //证明是普通表单字段 返回表单字段的name属性值
                String name=item.getFieldName();
                if(name.equals("username")){
                    out.print(item.getString("utf-8"));
                }
            }else{
            String filename =item.getName();
            String path    ="WEB-INF/upload/"; //相对路径  
            //就是讲相对路径转化成绝对路径
            String absolutePath =this.getServletContext().getRealPath(path);
            File file =new File(filename);
            File uploadFile =new File(absolutePath,file.getName());
                item.write(uploadFile);
                out.print("上传成功!"+filename);
            }
        }
        
    }
}
%>
posted @ 2016-07-04 08:24  锋锐之殇!  阅读(168)  评论(0编辑  收藏  举报