弹出提示框+CommonsMultipartFile+springMVC上传文件实例

目录结构如下:

WEB-INF/pages/error.jsp和WEB-INF/pages/index.jsps是必须要的,具体功能:

index.jsp:给出两个按钮,一个用于上传文件,一个用来开启模态框。
error.jsp:上传文件失败后,跳转的页面
在这里插入图片描述

添加pom.xml的dependency, 导入文件上传的jar包

	<dependency>
      <groupId>commons-fileupload</groupId>
      <artifactId>commons-fileupload</artifactId>
      <version>1.3</version>
    </dependency>

视图页面,index.jsp:

点击网站地图上传后,点击更新提交网站图片,弹出模态框后点击确定,如果没有跳转到error.jsp并且tomcat没有报错的话,文件上传应该是成功的,去项目更目录寻找就行了。
在这里插入图片描述

由于内置的<input type="file" />很丑,所以样式是自定义的。

<%@ page import="java.io.File" %>
<%@ page isELIgnored="false" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html lang="zh-CN">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Title</title>
    <link rel="stylesheet" href="//cdn.bootcss.com/bootstrap/3.3.5/css/bootstrap.min.css">
    <script src="//cdn.bootcss.com/jquery/1.11.3/jquery.min.js"></script>
    <script src="https://cdn.staticfile.org/popper.js/1.12.5/umd/popper.min.js"></script>
    <script src="//cdn.bootcss.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
</head>
<body>


<button type="button" class="btn btn-warning" data-toggle="modal" data-target="#myModal">更新提交网站图片
</button>
<form action="upload" enctype="multipart/form-data" method="post" onsubmit="">
    <%--<input type="file" name="multipartFile" class="btn-default" value="网站地图上传" id="filename"/>--%>
    <div class="col-xs-12 col-sm-4 col-md-4">
        <div class="file-container" style="display:inline-block;position:relative;overflow: hidden;vertical-align:middle">
            <button type="button" class="btn btn-default" style="width:150px;cursor:hand;">网站地图上传
            </button>
            <input type="file" id="jobData" onchange="loadFile(this.files[0])"
                   style="position:absolute;top:0;left:0;font-size:34px; opacity:0"
                   name="multipartFile" id="" accept="text/xml, application/xml">
        </div>
        <span id="filename" style="vertical-align: middle">未上传任何文件</span>
    </div>
    <script>
        function loadFile(file){
            $("#filename").html(file.name);
        }
    </script>
    <!--<input type="submit">-->
    <div class="modal fade" id="myModal" data-backdrop="false">
    <div class="modal-dialog">
        <div class="modal-content">

            <!-- 模态框头部 -->
            <div class="modal-header" style="text-align: center">
                <h4 class="modal-title">确认更新提交网站地图</h4>
                <button type="button" class="close" data-dismiss="modal">&times;</button>
            </div>

            <!-- 模态框主体 -->
            <div class="modal-body" style="text-align: center">
                更新提交网站地图“按钮”,会覆盖手动上传的sitemap文件
            </div>

            <!-- 模态框底部 -->
            <div class="modal-footer">
                <button type="submit" class="btn btn-primary">确认</button>
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
            </div>

        </div>
    </div>
</div>
</form>

<!--显示出你的项目的根目录,方便你找到上传的文件,也可以不要-->
<%= System.getProperty("evan.webapp").trim()%>

</body>

</html>

修改后index.jsp

<%@ page import="java.io.File" %>
<%@ page isELIgnored="false" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html lang="zh-CN">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Title</title>
    <link rel="stylesheet" href="//cdn.bootcss.com/bootstrap/3.3.5/css/bootstrap.min.css">
    <script src="//cdn.bootcss.com/jquery/1.11.3/jquery.min.js"></script>
    <script src="https://cdn.staticfile.org/popper.js/1.12.5/umd/popper.min.js"></script>
    <script src="//cdn.bootcss.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
</head>
<body>


<button type="button" class="btn btn-warning" onclick="checkFilename()" data-toggle="modal"
        id="btnCheckFilename"
        data-target="#myModal" >更新提交网站图片
</button>
<input value="${sep}" hidden id="sep"/>
<form action="upload" enctype="multipart/form-data" method="post" onsubmit="">
    <%--<input type="file" name="multipartFile" class="btn-default" value="网站地图上传" id="filename"/>--%>
    <div class="col-xs-12 col-sm-4 col-md-4">
        <div class="file-container" style="display:inline-block;position:relative;overflow: hidden;vertical-align:middle">
            <button type="button" class="btn btn-default" style="width:150px;cursor:hand;">网站地图上传
            </button>
            <input type="file" id="jobData" onchange="loadFile(this.files[0])"
                   style="position:absolute;top:0;left:0;font-size:34px; opacity:0"
                   name="multipartFile" accept="text/xml, application/xml">
        </div>
        <span id="filename" style="vertical-align: middle">未上传任何文件</span>
    </div>
    <script>

        function getFilename(){
            var fn = $("#jobData").val().trim();
            var sep = $("#sep").val();
            fn = fn.split(sep);
            fn = fn[fn.length-1];
            return fn;
        }
        function loadFile(file){
            $("#filename").html(file.name);
            var file = getFilename();
            if(file !== "sitemap.xml" && file !== "sitemap1.xml" && file!==
                "sitemap2.xml"){
                $("#btnCheckFilename").attr("disabled",true);
            }else{
                $("#btnCheckFilename").attr("disabled",false);
            }
        }
        function checkFilename(){
            var filename = getFilename();
            console.log(filename);
            if(filename != ""){
                if(filename !== "sitemap.xml" && filename !== "sitemap1.xml" && filename!==
                    "sitemap2.xml"){
                    location.reload();
                    alert("警告!您上传的格式错误,只允许上传名为sitemap.xml、sitemap1.xml、sitemap2.xml。");
                }
                $("#btnCheckFilename").addr("data-toggle", "modal");
            }else{
                $("#btnCheckFilename").removeAttr("data-toggle");
            }
        }
    </script>
    <%--<input type="submit">--%>
    <div class="modal fade" id="myModal" data-backdrop="false">
    <div class="modal-dialog">
        <div class="modal-content">

            <!-- 模态框头部 -->
            <div class="modal-header" style="text-align: center">
                <h4 class="modal-title">确认更新提交网站地图</h4>
                <button type="button" class="close" data-dismiss="modal">&times;</button>
            </div>

            <!-- 模态框主体 -->
            <div class="modal-body" style="text-align: center">
                更新提交网站地图“按钮”,会覆盖手动上传的sitemap文件
            </div>

            <!-- 模态框底部 -->
            <div class="modal-footer">
                <button type="submit" class="btn btn-primary">确认</button>
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
            </div>

        </div>
    </div>
</div>
</form>

<%--显示出你的项目的根目录,方便你找到上传的文件--%>
<%= System.getProperty("evan.webapp").trim()%>

</body>

</html>


Controller类

package com.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;


@Controller
public class UploadController{
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String showIndex(){
        return "index";
    }
    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    public String upload(MultipartFile multipartFile){
        if(!multipartFile.isEmpty()){
            //设置文件的保存路径
//            String filePath = "D:\\" + multipartFile.getOriginalFilename();
//            String filePath = "D:\\" + "网站地图123.txt";
            String filePath = System.getProperty("evan.webapp")+File.separator+ "网站地图123.XML";
            //转存文件
            try {
                multipartFile.transferTo(new File(filePath));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return "redirect:index";
    }
}

修改后的Controller类

package com.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;


@Controller
public class UploadController{
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String showIndex(ModelMap modelMap){
        modelMap.addAttribute("sep", File.separator);
        return "index";
    }
    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    public String upload(MultipartFile multipartFile){
        if(!multipartFile.isEmpty()){
            //设置文件的保存路径
//            String filePath = "D:\\" + multipartFile.getOriginalFilename();
//            String filePath = "D:\\" + "网站地图123.txt";
//            String relativelyPath=null;
            String filePath = System.getProperty("evan.webapp")+File.separator+ multipartFile.getOriginalFilename();
            //转存文件
            try {
                multipartFile.transferTo(new File(filePath));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return "redirect:index";
    }
}

在mvc-dispatcher-servlet.xml中(spring-servlet的xml文件)

以下两个java bean是必要的,不过视图解析器你可以看一下,本来的项目中应该就有

<!--ViewResolver 视图解析器-->
    <!--用于支持Servlet、JSP视图解析-->
    <bean id="jspViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
        <property name="prefix" value="/WEB-INF/pages/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
    <!-- 添加CommonsMultipartResolver的java bean实现上传文件-->
<bean id="multipartResolver"
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="defaultEncoding">
            <value>UTF-8</value>
        </property>
        <!--后面两个property可选,非必要-->
        <!--单次传输大小-->
        <property name="maxUploadSize">
            <value>32505856</value>
        </property>
        <!--缓冲区大小-->
        <property name="maxInMemorySize">
            <value>4096</value>
        </property>
    </bean>
    <!--上传文件后的页面跳转交给Spring来处理-->
    <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
        <property name="defaultErrorView" value="error"/>
    </bean>

web.xml中添加如下标签,以获取根目录。

  <!--获取根目录-->
  <context-param>
    <param-name>webAppRootKey</param-name>
    <param-value>evan.webapp</param-value>
  </context-param>
  <listener>
    <listener-class>org.springframework.web.util.WebAppRootListener</listener-class>
  </listener>

往上翻,在Controller中这样使用。
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值