详解SpringMVC实现图片上传以及该注意的小细节
先附上图片上传的代码
jsp代码如下:
<formaction="${path}/upload/uploadPic.do"method="post"enctype="multipart/form-data">
<div>

<inputtype="file"id="input-image"name="input-image">
<inputid="input-relative-path"name="imgs"type="hidden">
<inputid="input-last-path"type="hidden">
<inputtype="submit"value="上传图片">
</div>
</form>
controller代码:通过spring的方式实现
@Controller
@RequestMapping("/upload")
publicclassUploadControllerextendsBaseController{
@RequestMapping(value="/uploadPic",method=RequestMethod.POST)
@LoginCheck
publicvoiduploadPic(HttpServletRequestrequest,PrintWriterout,StringlastRealPath)throwsIOException{
//将当前上下文初始化给CommonsMultipartResolver
CommonsMultipartResolverresolver=newCommonsMultipartResolver(request.getSession().getServletContext());
//检查form中是否有enctype="multipart/form-data"
if(resolver.isMultipart(request)){
//强制转化request
MultipartHttpServletRequestreq=(MultipartHttpServletRequest)request;
//从表单获取input名称
Iterator<String>iterable=req.getFileNames();
//存在文件
if(iterable.hasNext()){
StringinputName=iterable.next();
//获得文件
MultipartFilemf=req.getFile(inputName);
byte[]mfs=mf.getBytes();
//定义文件名
StringfileName=newSimpleDateFormat("yyyyMMddHHmmssSSS").format(newDate());
Randomrandom=newRandom();
for(inti=0;i<3;i++){
fileName=fileName+random.nextInt(10);
}
//获得后缀名
StringoriFileName=mf.getOriginalFilename();
Stringsuffix=oriFileName.substring(oriFileName.lastIndexOf("."));
//上传图片到本地
StringlocalPath="/Users/ZR/Desktop/webPro/console/src/main/webapp/image/"+fileName+suffix;
mf.transferTo(newFile(localPath));
//获取图片的宽高
BufferedImagebufferedImage=ImageIO.read(newFileInputStream(newFile(localPath)));
intwidth=bufferedImage.getWidth();
intheight=bufferedImage.getHeight();
//获取文件大小
longsize=mf.getSize();
}
}
}
}
spring-mvc.xml代码:
<!-- 文件上传的视图解析器,id值是固定的 --> <beanid="multipartResolver"class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <propertyname="maxUploadSize"value="1024000"/> <!--其他属性--> </bean>
功能的实现其实很简单,但是对于初学者还是需要注意如下几个点
- form上的enctype="multipart/form-data"不能忘记。
- <inputtype="file"onchange="submitUpload()"id="input-image"name="input-image">的name标签可以随便取名,但是不能忽略,否则Iterator<String>iterable=req.getFileNames();这边获取的集合将为空。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。