Struts上传

从今天起开始写java学习笔记

 

 

1. Struts中的form为:TestForm.java

 

其中定义

 

//FormFile类型

 private FormFile file;

 

2.Struts中的aciton为:TestAction.java

//execute方法

public ActionForward execute(ActionMapping mapping, ActionForm form,
   HttpServletRequest request, HttpServletResponse response) throws FileNotFoundException, IOException {
  
  
  TestForm testForm = (TestForm) form;
  FormFile file = testForm.getFile();

  //获取文件名
  String filename = file.getFileName();
  System.out.println(filename);

  //获取绝对路径
  //String path = servlet.getServletContext().getRealPath("/data") + "//";
  //相对路径
  String path = "D://";
  System.out.println(path);
  
  //用IO读写
  try {
      InputStream stream = file.getInputStream();
      OutputStream bos = new FileOutputStream(path + file.getFileName());
      int bytesRead = 0;
              byte[] buffer = new byte[512];
              while ( (bytesRead = stream.read(buffer, 0, 512)) != -1) {
              bos.write(buffer, 0, bytesRead);
              }
              bos.close();
              stream.close();
              System.out.println("上传完成");
    }catch (FileNotFoundException e) {
              e.printStackTrace();
          } catch (IOException e) {
              e.printStackTrace();
          }
          return null;
 }

 

 

3.对应页面 test.jsp

 



 JSP for TestForm form


 

file :
  
  
filename :
  
  

  
  
 

 

你可能感兴趣的:(J2EE,struts,buffer,file,path,input,string)