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

 

<html>
<head>
 <title>JSP for TestForm form</title>
</head>
<body>
 <form name="testForm" method="post" action="/file/test.do" enctype="multipart/form-data">file : <input type="file" name="file" value="">
  
  <br />filename : <input type="text" name="filename" value="">
  
  <br />
  <input type="submit" value="Submit">
  <input type="submit" name="org.apache.struts.taglib.html.CANCEL" value="Cancel" οnclick="bCancel=true;">
 </form>
</body>
</html>

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值