struts2中文件上传下载

jsp:

<input type="file" name="blog.attachment"/>

1.定义上传bean类

    public class blog {

      private File attachment;//附件,和jsp页面的命名一致
      private String attachmentFileName;//固有写法,jsp页面文件名+FileName
      private String attachmentContentType;//固有写法,jsp页面文件名+ContentType

        //此处省略 set get 方法

    }

2.上传方法

        private Blog blog;

public Blog getBlog() {
return blog;
}
public void setBlog(Blog blog) {
this.blog = blog;
}

   第一种:将上传路径在方法中写死

   public void uploadFile(){

     File srcFile = blog.getAttachment();//获取页面中源文件位置

    String dest = ServletActionContext.getServletContext().getRealPath("/upload");//上传路径
    File destFile = new File(dest, blog.getAttachmentFileName());//在目标文件位置创建文件
   
    if(!destFile.exists())//如果文件不存在就创建一个
    destFile.mkdir();
   
    try {
FileUtils.copyFile(srcFile, destFile);//复制文件
} catch (IOException e) {
e.printStackTrace();
}

       //可以执行插入数据库的方法,但是最好是插入attachmentFileName,attachment是File类型,直接插入会有语法错误

   }

   第二种:在struts.xml中进行配置上传路径

   配置文件:

   <package name="blog" extends="struts-default">

        <action name="blogAction" class="action.BlogAction">
              <param name="uploadPath">/upload</param>
</action>
   </package>

   方法中只需修改这一句   

   String dest = ServletActionContext.getServletContext().getRealPath(uploadPath);

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值