用servlet+jsp实现的文件上传

     首先我们写两个jsp页面,一个upload.jsp用于编写客户端提交的表单,一个是result.jsp用向用户输出结果,然后编写服务器端程序servelt,我们只需要重写doPost方法既可。

    upload.jsp

 

<body>
<form action="/MyStructs2/UploadServlet" type="post" method="post" enctype="multipart/form-data">
  username:<input type="text" name="username"><br>
  password: <input type="password" name="password"><br>
  file1 <input type="file" name=file1><br>
  file2 <input type="file"  name=file2><br>
  <input type="submit" value="submit">
 </form>
 </body>

    result.jsp

<body>
     username:${requestScope.username}<br>
     password:${requestScope.password }<br>
      file1:  ${requestScope.file1}<br>
      file2:${requestScope.file2 }<br>
</body>

   UploadServlet.java

    DiskFileItemFactory factory=new DiskFileItemFactory();
           String path=request.getRealPath("/upload");
           factory.setRepository(new File(path));
           factory.setSizeThreshold(1024*1024);
           ServletFileUpload upload=new ServletFileUpload(factory);
         
         try {
			List<FileItem> list=upload.parseRequest(request);
			for(FileItem item:list)
			{
				if(item.isFormField())//如果不是文件类型
				{
					String name=item.getFieldName();
					String value=item.getString();
					request.setAttribute(name, value);
					
				}
				else//如果是文件类型
				{
					String name=item.getFieldName();//得到字段名称
					String value=item.getName();//取得该字段的值
					int start=value.lastIndexOf("\\");
					String fileName=value.substring(start+1);	//wenjianming 
					request.setAttribute(name, fileName);					
					OutputStream os=new FileOutputStream(new File(path,fileName));
					InputStream is=item.getInputStream();
					byte[] buffer=new byte[400];
					int length=0;
					while((length=is.read(buffer))>0)
					{
						
						os.write(buffer,0,length);
					}
					os.close();
				    is.close();
				}
				
			}
		} catch (FileUploadException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
                              request.getRequestDispatcher("upload/result.jsp").forward(request,response);//请求转发

 

你可能感兴趣的:(jsp,servlet,OS)