欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2024-02-24 22:33:40
多文件上传就是改良一个方法把multipartfile类换成commonsmultipartfile类,因为上传多个文件用数组方式的话multipartfile类不能初始化...

多文件上传就是改良一个方法把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多个文件上传及上传后立即显示图片功能,希望对大家有所帮助