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

目录结构如下:

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

index.jsp:给出两个按钮,一个用于上传文件,一个用来开启模态框。
error.jsp:上传文件失败后,跳转的页面
弹出提示框+CommonsMultipartFile+springMVC上传文件实例_第1张图片

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

	
      commons-fileupload
      commons-fileupload
      1.3
    

视图页面,index.jsp:

点击网站地图上传后,点击更新提交网站图片,弹出模态框后点击确定,如果没有跳转到error.jsp并且tomcat没有报错的话,文件上传应该是成功的,去项目更目录寻找就行了。
弹出提示框+CommonsMultipartFile+springMVC上传文件实例_第2张图片

由于内置的很丑,所以样式是自定义的。

<%@ 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>Titletitle>
    <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>
    
    <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">×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>Titletitle>
    <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">×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是必要的,不过视图解析器你可以看一下,本来的项目中应该就有


    
    <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>
    
<bean id="multipartResolver"
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="defaultEncoding">
            <value>UTF-8value>
        property>
        
        
        <property name="maxUploadSize">
            <value>32505856value>
        property>
        
        <property name="maxInMemorySize">
            <value>4096value>
        property>
    bean>
    
    <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
        <property name="defaultErrorView" value="error"/>
    bean>

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

  
  <context-param>
    <param-name>webAppRootKeyparam-name>
    <param-value>evan.webappparam-value>
  context-param>
  <listener>
    <listener-class>org.springframework.web.util.WebAppRootListenerlistener-class>
  listener>

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

你可能感兴趣的:(JavaWeb)