Spring mvc JS上传文件
2015-09-28 09:57
585 查看
在Spring mvc xml 中添加
上传图片代码
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!-- 指定所上传文件的总大小不能超过800KB......注意maxUploadSize属性的限制不是针对单个文件,而是所有文件的容量之和 --> <property name="maxUploadSize" value="500000"/> </bean> <bean id="exceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver"> <property name="exceptionMappings"> <props> <!-- 遇到MaxUploadSizeExceededException异常时,跳转到/page/html/errorGolbal.html页面 --> <prop key="org.springframework.web.multipart.MaxUploadSizeExceededException">/page/errorGolbal</prop> </props> </property> </bean>
上传图片代码
@ResponseBody @RequestMapping("/fileUpload") public String fileUpload( @RequestParam MultipartFile[] myfiles, HttpServletRequest request, HttpServletResponse response) throws Exception{ String realPath = request.getSession().getServletContext().getRealPath("/upload/article"); response.setContentType("text/plain; charset=UTF-8"); PrintWriter out = response.getWriter(); long fileSize = 0; int height = 0; int width = 0; String fileName = null; String path = null; for(MultipartFile myfile : myfiles){ if(myfile.isEmpty()){ out.print("{\"message\":\"请选择图片再次上传!!\",\"status\":-1}"); out.flush(); return null; }else{ try { SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss"); fileSize = myfile.getSize(); //图片大小 String str = myfile.getOriginalFilename(); String suffix = str.substring(str.indexOf(".")); String name = str.substring(0, str.indexOf(".")); fileName = MD5Util.md5Encode(df.format(new Date()))+suffix; //名称 FileUtils.copyInputStreamToFile(myfile.getInputStream(), new File(realPath, fileName)); } catch (Exception e) { out.print("{\"message\":\"上传失败\",\"status\":-1}"); out.flush(); return null; } } } path = request.getContextPath() + "/upload/article/" + fileName; //url路径 String filepath = request.getContextPath() + "/upload/article/"; BufferedImage bufferedImage = ImageIO.read(new File(realPath+'/'+fileName)); width = bufferedImage.getWidth(); //宽度 height = bufferedImage.getHeight(); //高度 out.print("{\"data\":{\"path\":\""+path+"\",\"size\":\""+fileSize+"\",\"width\":\""+width+"\",\"height\":\""+height+"\",\"fileName\":\""+fileName+"\",\"filepath\":\""+filepath+"\"},\"status\":1}"); out.flush(); return null; }
相关文章推荐
- java对世界各个时区(TimeZone)的通用转换处理方法(转载)
- java-注解annotation
- java-模拟tomcat服务器
- java-用HttpURLConnection发送Http请求.
- java-WEB中的监听器Lisener
- Android IPC进程间通讯机制
- Android Native 绘图方法
- Android java 与 javascript互访(相互调用)的方法例子
- 介绍一款信息管理系统的开源框架---jeecg
- 聚类算法之kmeans算法java版本
- java实现 PageRank算法
- PropertyChangeListener简单理解
- 插入排序
- 冒泡排序
- 堆排序
- 快速排序
- 二叉查找树
- [原创]java局域网聊天系统