Struts2 框架文件上传

1.提交方式必须是post
2.表单中的上传项必须有name属性
3.表单的 enctype 属性必须是multipart/form-data

Action中:

    //文件上传需要的参数
    private File upload;//上传的文件
    private String uploadFileName; //接收文件名
    private String uploadContextType;//接收文件类型

    public void setUpload(File upload) {
        this.upload = upload;
    }
    public void setUploadFileName(String uploadFileName) {
        this.uploadFileName = uploadFileName;
    }
    public void setUploadContextType(String uploadContextType) {
        this.uploadContextType = uploadContextType;
    }
    public void setCategorySecondService(CategorySecondService categorySecondService) {
        this.categorySecondService = categorySecondService;
    }

    public String save() {
        product.setPdate(new Date());
        if(upload != null) {
            //获得文件上传的磁盘绝对路劲
            String realPath =  ServletActionContext.getServletContext().getRealPath("/products");
            //创建一个文件
            File disFile = new File(realPath+"//"+uploadFileName);
            //文件上传
            try {
                FileUtils.copyFile(upload, disFile);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            product.setImage("products/"+uploadFileName);

        }
        //将数据保存到数据库
        productService.save(product);
        return "savesuccess";
    }



jsp代码:

<tr>
    <td  width="18%" align="center" class="ta_01" bgColor="#ffffff">
    商品图片:
    </td>
    <td class="ta_01" bgColor="#ffffff">                
    <input type="file" name="upload"/>
    </td>
</tr>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值