Spring MVC 图片上传

引入需要的包

        <dependency>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
            <version>1.1</version>
        </dependency>
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.4</version>
        </dependency>
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.2.2</version>
        </dependency>


Html代码

                <tr>
                    <td class="labelTd">
                        箱子图片
                    </td>
                    <td>
                        <input type="text" style="width: 100px;" value="" id="image" validType="isImage" class="easyui-validatebox">
                        <input type="file" value="" name="file" id="file" οnchange="image.value=this.value" style="float:left;margin-top:-20px; *margin-top:-40px; filter:alpha(opacity=0);-moz-opacity:0;opacity:0;"/>
                    </td>
                </tr>

后台处理

    @Override
    public void insertBox(Box box,MultipartFile file) throws Throwable{
        String path1,path2,path,fileName;
        BusinessException businessException = new BusinessException();//异常处理
        if(!file.isEmpty()){
            int location =file.getOriginalFilename().lastIndexOf(".");
            String fileType = file.getOriginalFilename().substring(location+1);//文件后缀
            SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMddHHmmssS");//重命名文件名称
            fileName = sdf.format(new Date())+"."+fileType;
            String[] suffixs=fileName.split("\\.");
            String suffix = "."+suffixs[suffixs.length-1];
            if((".jpg.png.gif.jpeg".indexOf(suffix.toLowerCase())!=-1)){
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
                path1 = ClassUtils.getDefaultClassLoader().getResource("../../").getPath();//项目路径
                path2 = "upload/box_image/"+dateFormat.format(new Date());//存放路径
                path = path1+path2;
                FileUtils.createDir(path);//如果没有此目录则创建
                file.transferTo(new File(path +"/"+ fileName));//上传
                box.setBoxImage("../"+path2 + "/" +fileName);//获取文件路径,放入数据库
            }else{
                businessException.setCode(MessageConstants.IMAGE_FORMAT_ERROR);
                throw businessException;
            }
        }
        box.setCreateTime(new Date());
        int result = boxDao.insert(box);
        //int result = 1;
        if(result != 1){
            businessException.setCode(MessageConstants.INSERT_BOX_FAIL);
            throw businessException;
        }
    }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值