Spring MVC 图片上传

来源:互联网 发布:重阳节算法定节假日吗 编辑:程序博客网 时间:2024/04/30 06:48

引入需要的包

        <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" onchange="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;        }    }


0 0