SpringMVC的图片(文件)上传

来源:互联网 发布:ubuntu挂载命令 编辑:程序博客网 时间:2024/04/28 02:34

最近要用SpringMVC做个图片上传的功能,文件上传也可以用,下面是一些需要注意的地方。

1、页面

<form id="action" method="post" enctype="multipart/form-data">

页面上form表单上需加上enctype="multipart/form-data"属性。

2、配置文件

springmvc的配置文件中加上以下配置

<!-- 文件上传 -->    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">        <!-- 设置上传文件总大小限制 -->        <property name="maxUploadSize" value="20000000"></property>    </bean>

后台接收并上传:

因为这里是一次性上传了三张图片所以用MultipartFile[]数组接收

@RequestMapping(value = "/uploadimg", method = RequestMethod.POST)@ResponseBodypublic Result addBankImg(@RequestParam MultipartFile[] file,BankManage bankManage,HttpServletRequest request) throws Exception{Result result = new Result();int i = 0;for (MultipartFile myfile : file) {i = i + 1;if (!myfile.isEmpty()) {//判断文件是否为空,为空则不上传String path = request.getSession().getServletContext().getRealPath("images");String imageFileName = i + new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date()) + ".png";File targetFile = new File(path, imageFileName);if (!targetFile.exists()) {targetFile.mkdirs();}try{//上传myfile.transferTo(targetFile);}catch(Exception e){e.printStackTrace();}}}result.setSuccess(true);result.setMsg("添加成功!");return result;}


到这里基本就完成了。


这是MultipartFile类的几个常用方法:

String getContentType()  获取文件MIME类型
InputStream getInputStream()  获取上传文件流
String getName()   获取表单中文件组件的名字
String getOriginalFilename()   获取上传文件的原名
long getSize()   获取文件的字节大小,单位byte
boolean isEmpty()   上传文件是否为空
void transferTo(File dest)   保存到一个目标文件中。



0 0
原创粉丝点击