温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

SpringMVC如何实现多个文件上传及上传后立即显示图片功能

发布时间:2021-07-10 10:18:23 来源:亿速云 阅读:141 作者:小新 栏目:编程语言

这篇文章主要为大家展示了“SpringMVC如何实现多个文件上传及上传后立即显示图片功能”,内容简而易懂,条理清晰,希望能够帮助大家解决疑惑,下面让小编带领大家一起研究并学习一下“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("<h2>当前浏览器不支持FileReader接口</h2>");   }    //选择图片,马上预览   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如何实现多个文件上传及上传后立即显示图片功能”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注亿速云行业资讯频道!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI