本文主要是介绍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>
后台处理
@Overridepublic 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;}}
这篇关于Spring MVC 图片上传的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!