ssh项目中的文件上传

上传文件要添加两个jar包commonse,在pom中添加

<!--文件上传,添加这个就直接帮助我们自动添加其他所需的依赖-->
      <dependency>
          <groupId>commons-io</groupId>
          <artifactId>commons-io</artifactId>
          <version>2.5</version>
      </dependency>
        <!--javax  获取文件路径的时候使用-->
      <dependency>
          <groupId>javax.servlet</groupId>
          <artifactId>javax.servlet-api</artifactId>
          <version>3.1.0</version>
      </dependency>

页面中的配置,要使用post方式提交,添加属性enctype="multipart/form-data"

<form method="post" action="/fileUpload.action" enctype="multipart/form-data"  >
    <input name="user" />
    <input name="pass"/>
    <input type="file" name="file"/>
    <button type="submit">提交</button>
</form>

在action中的配置,添加三个属性,这三个属性必须要创建,否则会报错.当然不要忘记set/get方法

    public File file;//io包中的file
    public String fileFileName;//接收到的文件的名字
    public String   fileContentType;//接收到的文件的类型

上传文件的方法如下

 @Action(value = "/fileUpload" ,results = {@Result(name = "success" ,location = "/seccess.jsp",type = "redirect")})
    public String fileUpload() throws IOException {
        //获得输入流,读取文件的内容
        FileInputStream fileInputStream=new FileInputStream(file);
        byte[] b=new byte[102400];
        fileInputStream.read(b);
        //获取项目系统路径
        HttpServletRequest request = ServletActionContext.getRequest();
        //获取文件的路径
        String  path=request.getServletContext().getRealPath(fileFileName);
        //获取最后一个斜杠的位置
        int weizhi = path.lastIndexOf("\\");
        //将文件的路径进行改写
        String newPath = path.substring(0, weizhi);
        File newFile=new File(newPath+"\\file\\"+fileFileName);
        //将文件写入上面定义的文件夹中
        FileOutputStream fileOutputStream=new FileOutputStream(newFile);
        fileOutputStream.write(b);
        fileInputStream.close();
        fileOutputStream.close();
        return "success";
    }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值