SpringMVC多个文件上传及上传后立即显示图片功能
时间:2020-10-09 22:42:20|栏目:JAVA代码|点击: 次
多文件上传就是改良一个方法把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>
总结
栏 目:JAVA代码
下一篇:深入分析JAVA Vector和Stack的具体用法
本文标题:SpringMVC多个文件上传及上传后立即显示图片功能
本文地址:http://www.codeinn.net/misctech/9108.html
阅读排行
- 1Java Swing组件BoxLayout布局用法示例
- 2java中-jar 与nohup的对比
- 3Java邮件发送程序(可以同时发给多个地址、可以带附件)
- 4Caused by: java.lang.ClassNotFoundException: org.objectweb.asm.Type异常
- 5Java中自定义异常详解及实例代码
- 6深入理解Java中的克隆
- 7java读取excel文件的两种方法
- 8解析SpringSecurity+JWT认证流程实现
- 9spring boot里增加表单验证hibernate-validator并在freemarker模板里显示错误信息(推荐)
- 10深入解析java虚拟机