SpringMVC多个文件上传及上传后立即显示图片功能
多文件上传就是改良一个方法把MultipartFile类换成CommonsMultipartFile类,因为上传多个文件用数组方式的话MultipartFile类不能初始化,它不支持数组
package com.meng.upload; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import javax.servlet.http.HttpServletRequest; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.commons.CommonsMultipartFile; @Controller public class upload { @RequestMapping(value="/upload",method=RequestMethod.POST) public String upload(@RequestParam("file1") CommonsMultipartFile[] file1, HttpServletRequest request) { for (CommonsMultipartFile commonsMultipartFile : file1) { try { File file = new File(request.getServletContext().getRealPath("upload"), System.currentTimeMillis() + "_" + commonsMultipartFile.getOriginalFilename()); System.out.println(file.getPath()+""); FileOutputStream fileOutputStream = new FileOutputStream(file); fileOutputStream.write(commonsMultipartFile.getBytes()); fileOutputStream.close(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } return "ok"; } }
index.jsp页面上传立即显示图片
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <html> <head> <title>My JSP 'index.jsp' starting page</title> <script type="text/javascript"> //判断浏览器是否支持FileReader接口 if (typeof FileReader == 'undefined') { alert("<h1>当前浏览器不支持FileReader接口</h1>"); } //选择图片,马上预览 function xmTanUploadImg(obj) { var file = obj.files[0]; var reader = new FileReader(); reader.onload = function(e) { var img = document.getElementById("img1"); img.src = e.target.result; } reader.readAsDataURL(file); } </script> </head> <body> <form action="upload.upload" method="post" enctype="multipart/form-data"> file1::<input type="file" name="file1" accept=".jpg,.png" onchange="xmTanUploadImg(this)" /> <input type="submit" /> <img id="img1" /> </form> </body> </html>
总结
以上所述是小编给大家介绍的SpringMVC多个文件上传及上传后立即显示图片功能,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对脚本之家网站的支持!
相关文章
java.lang.Runtime.exec() Payload知识点详解
在本篇文章里小编给大家整理的是一篇关于java.lang.Runtime.exec() Payload知识点相关内容,有兴趣的朋友们学习下。2020-03-03Spring Boot项目@RestController使用重定向redirect方式
这篇文章主要介绍了Spring Boot项目@RestController使用重定向redirect方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教2021-09-09IntelliJ IDEA语法报错"Usage of API documented as @since 1.6+"的解决
今天小编就为大家分享一篇关于IntelliJ IDEA语法报错"Usage of API documented as @since 1.6+"的解决办法,小编觉得内容挺不错的,现在分享给大家,具有很好的参考价值,需要的朋友一起跟随小编来看看吧2018-10-10java web开发中大量数据导出Excel超时(504)问题解决
开发测试时候导入数据遇到大数据导入的问题,整理了下,需要的朋友可以参考下2017-04-04
最新评论